I would like to slice an array a in Julia in a loop in such a way that it's divided in chunks of n samples. The length of the array nsamples is not a multiple of n, so the last stride would be shorter.
My attempt would be using a ternary operator to check if the size of the stride is greater than the length of the array:
for i in 0:n:nsamples-1
end_ = i+n < nsamples ? i+n : end
window = a[i+1:end_]
end
In this way, a[i+1:end_] would resolve to a[i+1:end] if I'm exceeding the size of the array.
However, the use of the keyword "end" in line 2 is not acceptable (it's also the keyword for "end of control statement" in julia.
In python, I can assign None to end_ and this would resolve to a[i+1:None], which will be the end of the array.
How can I get around this?
The end keyword is only given this kind of special treatment inside of indexing expressions, where it evaluates to the last index of the dimension being indexed. You could put it inside with e.g.
for i in 0:n:nsamples-1
window = a[i+1:min(i+n, end)]
end
Or you could just use length(a) (or nsamples, I guess they are the same?) instead of end to make it clear which end you are referring to.
Ugly way:
a=rand(7);
nsamples=7;
n=3;
for i in 0:n:nsamples-1
end_ = i+n < nsamples ? i+n : :end
window = #eval a[$i+1:$end_]
println(window)
end
Better solution:
for i in 0:n:nsamples-1
window = i+n < nsamples ? a[i+1:i+n] : a[i+1:end]
println(window)
end
In order to simplify the loop (and perhaps improve performance) the last partial window can be processed after the loop. This is recommended since it usually requires some special processing anyway. In code:
i = 0 # define loop variable outside for to retain it after
for i=n:n:length(a)
println(a[(i-n+1):i])
end
i < length(a) && println(a[(i+1):end])
The last bit can be done with an if but && is pretty clear.
Related
Below is a MATLAB code (recursion) which inputs a vector (l_1,l_2,...,l_r) of non negative integers and an integer m prints all sequences (m_1,m_2,...,m_r) satisfying:
0 <= m_i <= l_i for all 1 <= i <= r and m_1 + m_2 + ... + m_r = m
The r is captured in the function definition by calling the size of the (l_i) array below:
function arr=sumseq(m,lims)
arr=[];
r=size(lims,2);
if r==0 || m<0
arr=[];
elseif r==1 && lims(1)>=m
arr=[m]; %#ok<NBRAK>
else
for i=0:lims(1)
if(lims(1)<0)
arr=[];
else
v=sumseq(m-i,lims(2:end));
arr=[arr;[i*ones(size(v,1),1) v]];
end
end
end
end
Here what I have done is, stored a whole array of them and made it my output. Instead I want to only print them one by one and not store them in an array. This seems simple enough as there is not much choice in which line(s) I need to change (I believe it is the contents of the else block inside the for loop), but I get into a fix every time I try to achieve it.
(Also, MATLAB warned me that if I kept re-initializing the array with a larger array like in the statement:
arr=[arr;[i*ones(size(v,1),1) v]];
it reallocates a fresh array for all the contents of arr and spends a 'lot' of time doing so.)
In short: recursion or not, I want to save the trouble of storing it, and need an algorithm which is as efficient as or more efficient than what I have here.
Working in MATLAB R2017a. I'm trying to optimise a piece of code I'm working on. It uses arrays to store field values on a grid.
In order to create a specific function in a field array I originally used the straight forward method of two for loops iterating over all the array elements. But i know for loops are slow so since then I came back and tried my best to remove them. However I could only manage to remove one of the loops; leaving me with this:
for n = 1:1:K
%%% define initial pertubation
t=n*dt;
% create array for source Ez field.
xtemps = (1:Ng)*dX;
for k = 1:Ng
ztemp = k*dX;
Ez0(k,:) = THzamp * (1/(1+exp(-(t-stepuppos)))) * exp(-((xtemps-...
THzstartx).^2)./(bx^2)) .* (t-((ztemp-THzstartz)/vg))*exp(-((t-((ztemp-...
THzstartz)/vg))^2)/(bt^2));
end
The important bit here is the last 5 lines, but I figured the stuff before might be important for context. I've removed the for loop looping over the x coordinates. I want to vectorize the z/k for loop but I can't figure out how to distinguish between the dimensions with the array oporators.
Edit: THzamp, stepuppos, bx, bt, THzstartz, THzstartx are all just scalars, they control the function (Ez0) I'm trying to create. dX and t are also just scalars. Ez0 is a square array of size Ng.
What I want to achieve is to remove the for loop that loops over k, so that that the values of ztemp are defined in a vector (like xtemps already is), rather than individually in the loop. However, I don't know how I'd write the definition of Ez0 in that case.
First time posting here, if I'm doing it wrong let me know. If you need more info just ask.
It isn't clear if n is used in the other headers and as stated in the comments your sizes aren't properly defined so you'll have to ensure the sizes are correct.
However, you can give this vectorize code a try.
n = 1:K
%%% define initial pertubation
t=n*dt;
% create array for source Ez field.
xtemps = (1:Ng)*dX;
for k = 1:Ng
ztemp = k*dX;
Ez0(k,:) = THzamp .* (1./(1+exp(-(t-stepuppos)))) .* exp(-((xtemps-...
THzstartx).^2)./(bx^2)) .* (t-((ztemp-THzstartz)/vg)).*exp(-((t-((ztemp-...
THzstartz)/vg)).^2)/(bt.^2));
end
So now t has the size K you'll need to ensure stepupposand (ztemp-THzstartz)/vg) have the same size K. Also you can take a look at vectors vs array operators here.
I'm trying to read in multiple files (csv, 2 columns) with belonging names (String) and interpolation methods smoothness (String). By using a record I get a nice GUI in Dymola:
To explain my problem, here is a simplified model:
model Test_Strings
parameter String x[:];
parameter Integer k = size(x,1);
Integer i;
initial algorithm
i := 0;
Modelica.Utilities.Streams.print(String(i));
Modelica.Utilities.Streams.print(String(k));
equation
algorithm
when sample(1,1) then
i :=pre(i) + 1;
Modelica.Utilities.Streams.print(String(i));
for j in 1:k loop
Modelica.Utilities.Streams.print(x[j]);
end for;
end when;
end Test_Strings;
The GUI for this looks as follows:
The code to run it:
model Test_Strings_System
Test_Strings test_Strings(x={"a","b","c","d"});
end Test_Strings_System;
This will give the following result in the console:
Now, if I try to use a record:
record MyRecord2
parameter String name = "NoName";
end MyRecord2;
And adapt the model (only the first parameter line MyRecord2 x[:] and within the for loop x[j].name changed):
model Test_Strings2
parameter MyRecord2 x[:];
parameter Integer k = size(x,1);
Integer i;
initial algorithm
i := 0;
Modelica.Utilities.Streams.print(String(i));
Modelica.Utilities.Streams.print(String(k));
equation
algorithm
when sample(1,1) then
i :=pre(i) + 1;
Modelica.Utilities.Streams.print(String(i));
for j in 1:k loop // k must be fixed number if equation
Modelica.Utilities.Streams.print(x[j].name); // j must be fixed number if algorithm
end for;
end when;
end Test_Strings2;
Then I get a translation error: Internal error: failed to expand string.
If I fix k or j within the for loop to a given number (let's say 3) then it works, but depending if it's within an algorithm or equation section (see comments within code).
I had similar problems with flexible array sizes and still don't understand how to solve it.
Do I have to use functions?
How can I use flexible array sizes which are defined depending on external data, selected as parameters prior to simulation (e.g. the length of a table)?
Or is the problem in this case somewhere else?
Thanks.
You can change the model to have an array of records as visible parameters, but internally use an array of strings (tested with Dymola 2017 and later):
model Test_Strings2
parameter MyRecord2 x[:];
parameter Integer k = size(x,1);
Integer i;
protected
parameter String s[:]=x.name; // Hack
initial algorithm
i := 0;
Modelica.Utilities.Streams.print(String(i));
Modelica.Utilities.Streams.print(String(k));
equation
algorithm
when sample(1,1) then
i :=pre(i) + 1;
Modelica.Utilities.Streams.print(String(i));
for j in 1:k loop
Modelica.Utilities.Streams.print(s[j]);
end for;
end when;
end Test_Strings2;
I'm looking to perform the cross-correlation* operation using an FPGA.
The secific part that I am currently struggling with is the multiplication piece. I want to multiply each 8-bit element of a nx8 shift register that uses excess or offset representation** against a nx1 shift register where I treat 0s as a -1 for the purposes of multiplication.
Now if I was doing that for a single element, I might do something like this for the operation:
input [7:0] dataIn;
input refIn;
output [7:0] dataOut;
wire [7:0] dataOut;
wire [7:0] invertedData;
assign invertedData = 8'd0 - dataIn;
assign dataOut <= refIn ? dataIn : invertedData;
What I'm wondering is how do I scale this to 4, 8, n elements?
My first though was to use a for loop like this:
for(loop=0; loop < n; loop = loop+1)
begin
assign invertedData[loop*8+7:loop*8] = 8'd0 - dataIn[loop*8+7:n*8];
assign dataOut[loop*8+7:loop*8] <= refIn[loop] ? dataIn[loop*8+7:loop*8] : invertedData[loop*8+7:loop*8];
end
This doesn't compile, but that's more or less the idea, and I can't seem to find the right syntax to do what I want.
https://en.wikipedia.org/wiki/Cross-correlation
** http://www.cs.auckland.ac.nz/~patrice/210-2006/210%20LN04_2.pdf
for(loop=0; loop < n; loop = loop+1)
begin
assign invertedData[n*8+7:n*8] = 8'd0 - dataIn[n*8+7:n*8];
assign dataOut[n*8+7:n*8] <= refIn[n] ? dataIn[n*8+7:n*8] : invertedData[n*8+7:n*8];
end
There's a few issues with this, but I think you can make this work.
You can't have 'assign' statements in a for loop. A for loop is meant to be used inside a begin/end block, so you need to change invertedData/dataOut from wire type to reg type, and remove the assign statements.
You generally can't have variable part-selects, unless you use the special constant-width selection operator (verilog-2001 support required). That would look like this: dataIn[n*8 +:8], which means: select 8 bits starting from n*8.
I don't know about your algorithm, but it looks like loop/n are backwards in your statement. You should be incrementing n, not loop variable (or else all statements will be operating on the same part-select).
So considering those points I believe this should compile for you:
always #* begin
for(n=0; n< max_loops ; n=n+1)
begin
invertedData[n*8 +:8] = 8'd0 - dataIn[n*8 +:8];
dataOut[n*8 +:8] <= refIn[n] ? dataIn[n*8 +:8] : invertedData[n*8 +:8];
end
end
So I have an array x(i,j) which is inside a loop k = 1 to n, where n is set by the user. It updates every time I go to the next k. I was wondering if it's possible to save each of the arrays created in the loop to the memory so I can recall them at another time?
So for example, I was thinking I could do something along the lines of:
For k = 1 to n
...
SavedArray(k) = x(i,j)
...
next k
So I could recall, say for example, SavedArray(58) which would have been the 58th iteration of the loop.
Is this feasible?
Thanks for your time.
It depends what is X, and what you wish to save.
If X(i,j) is just Integer so just make a new array and save it : MyArr(k) = X(i,j)
If X(i,j) is array (so X is 2D of 1D array ~ 3D) -you can use Array of Arrays to save it.
To simplify the solution you can create a new type, let say:
Public Type typeArray
X(1 To 10) As Integer
Y(1 To 10) As Integer
End Type
And Declare:
Public SavedArray(1 To 10) As typeArray
Now you can use it as you wish.