Is there a way to get the value of an array to the shape of a variable? Even when I select a single value of an array, say A(1:1, 1:1), it still complains when I compile and want to assign this to a variable:
Error: Incompatible ranks 0 and 1 in assignment at (1)
The goal in the end is something like this:
H = MAXVAL(matrix) - epsilon
IF ( matrix(i:i, i:i) >= H ) THEN
...
but I cannot make this comparison because H is a variable and matrix(i:i, i:i) a 1x1 array. Is the only possibility for this to work to make H and array, too?
Thank you for your help!
Do not specify a range, use a single element:
A(1,1)=1
Your statement would then read:
H = MAXVAL(matrix) - epsilon
IF ( matrix(i, i) >= H ) THEN
Background:
Fortran allows you to work on sub-arrays like:
A(1:10,2:5)
which would be a 10x4 array. So A(1:1,1:1) is in fact an array (1x1) (as you noted). A(1,1), on the other hand, is a scalar and can be treated as such.
Related
I'm pretty new to matlab, so I'm guessing there is some shortcut way to do this but I cant seem to find it
results = eqs\soltns;
A = results(1);
B = results(2);
C = results(3);
D = results(4);
E = results(5);
F = results(6);
soltns is a 6x1 vector and eqs is a 6x6 matrix, and I want the results of the operation in their own separate variables. It didn't let me save it like
[A, B, C, D, E, F] = eqs\soltns;
Which I feel like would make sense, but it doesn't work.
Up to now, I have never come across a MATLAB function doing this directly (but maybe I'm missing something?). So, my solution would be to write a function distribute on my own.
E.g. as follows:
result = [ 1 2 3 4 5 6 ];
[A,B,C,D,E,F] = distribute( result );
function varargout = distribute( vals )
assert( nargout <= numel( vals ), 'To many output arguments' )
varargout = arrayfun( #(X) {X}, vals(:) );
end
Explanation:
nargout is special variable in MATLAB function calls. Its value is equal to the number of output parameters that distribute is called with. So, the check nargout <= numel( vals ) evaluates if enough elements are given in vals to distribute them to the output variables and raises an assertion otherwise.
arrayfun( #(X) {X}, vals(:) ) converts vals to a cell array. The conversion is necessary as varargout is also a special variable in MATLAB's function calls, which must be a cell array.
The special thing about varargout is that MATLAB assigns the individual cells of varargout to the individual output parameters, i.e. in the above call to [A,B,C,D,E,F] as desired.
Note:
In general, I think such expanding of variables is seldom useful. MATLAB is optimized for processing of arrays, separating them to individual variables often only complicates things.
Note 2:
If result is a cell array, i.e. result = {1,2,3,4,5,6}, MATLAB actually allows to split its cells by [A,B,C,D,E,F] = result{:};
One way as long as you know the size of results in advance:
results = num2cell(eqs\soltns);
[A,B,C,D,E,F] = results{:};
This has to be done in two steps because MATLAB does not allow for indexing directly the results of a function call.
But note that this method is hard to generalize for arbitrary sizes. If the size of results is unknown in advance, it would probably be best to leave results as a vector in your downstream code.
Is there a way to create an array of sets in Matlab.
Eg: I have:
a = ones(10,1);
b = zeros(10,1);
I need c such that c = [(1,0); (1,0); ...], i.e. each set in c has first element from a and 2nd element from b with the corresponding index.
Also is there some way I can check if an unknown set (x,y) is in c.
Can you all please help me out? I am a Matlab noob. Thanks!
There are not sets in your understanding in MATLAB (I assume that you are thinking of tuples on Python...) But there are cells in MATLAB. That is a data type that can store pretty much anything (you may think of pointers if you are familiar with the concept). It is indicated by using { }.
Knowing this, you could come up with a cell of arrays and check them using cellfun
% create a cell of numeric arrays
C = {[1,0],[0,2],[99,-1]}
% check which input is equal to the array [1,0]
lg = cellfun(#(x)isequal(x,[1,0]),C)
Note that you access the address of a cell with () and the content of a cell with {}. [] always indicate arrays of something. We come to this in a moment.
OK, this was the part that you asked for; now there is a bonus:
That you use the term set makes me feel that they always have the same size. So why not create an array of arrays (or better an array of vectors, which is a matrix) and check this matrix column-wise?
% array of vectors (there is a way with less brackets but this way is clearer):
M = [[1;0],[0;2],[99;-1]]
% check at which column (direction ",1") all rows are equal to the proposed vector:
lg = all(M == [0;2],1)
This way is a bit clearer, better in terms of memory and faster.
Note that both variables lg are arrays of logicals. You can use them directly to index the original variable, i.e. M(:,lg) and C{lg} returns the set that you are looking for.
If you would like to get logical value regarding if p is in C, maybe you can try the code below
any(sum((C-p).^2,2)==0)
or
any(all(C-p==0,2))
Example
C = [1,2;
3,-1;
1,1;
-2,5];
p1 = [1,2];
p2 = [1,-2];
>> any(sum((C-p1).^2,2)==0) # indicating p1 is in C
ans = 1
>> any(sum((C-p2).^2,2)==0) # indicating p2 is not in C
ans = 0
>> any(all(C-p1==0,2))
ans = 1
>> any(all(C-p2==0,2))
ans = 0
Followup to my previous question now I have a problem with the shape of the bounds array in the constrained bfgs method.
My code is the following:
nr = 5
lag = 1
guess =numpy.array([[[ random.uniform(-1.0,1.0) for k in range(nr)] for l in range(lag)],
[[ random.uniform( 0.0,1.0) for k in range(nr)] for l in range(lag)],
[[ random.uniform(-1.0,1.0) for k in range(nr)] for l in range(lag)]])
bounds =numpy.array([[[ [-1.0,1.0] for k in range(nr)] for l in range(lag)],
[[ [ 0.0,1.0] for k in range(nr)] for l in range(lag)],
[[ [-1.0,1.0] for k in range(nr)] for l in range(lag)]])
result = optimize.fmin_l_bfgs_b( myfunc,guess.flatten(),bounds=bounds.reshape(15,2) )
As you can see I start out with a (3,1,5) shaped list of lists, which is my preferred format with which I work inside the myfunc() because it's easy to parse with nested for loops.Then this list gets crunched into a (15,) shaped numpy array to satisfy the x0 parameter's format needs, but don't worry because the X value inside the myfunc() is then transformed back into my (3,1,5) format via X=X.reshape(origshape) where the origshape global variable will save the original format. It may seem inefficient and a useless back and forth but I couldn't find a way to do it easier.
Now this works with every fmin_ function so far except with bounds like fmin_l_bfgs_b, I couldn't figure out what shape the bounded values need to be in. The documentation says:
"(min, max) pairs for each element in x, defining the bounds on that parameter."
So I thought this means 1 pair for each element, so a (15,2) shape in my situation, but when I use the code above, it gives me the following error:
TypeError: 'float' object is not subscriptable
So I guess I got the shape wrong. Please help me to fix this.
result = optimize.fmin_l_bfgs_b( myfunc,guess.flatten(),bounds=bounds.reshape(15,2),approx_grad=True )
It seems like it doesn't work without setting the approx_grad variable to True. Otherwise I guess you need to specify the fprime function.
Either way the function seems to be depreciated and using the scipy.optimize.minimize function is better.
I am trying to create 46 variables, indexed from 0-45 dependent on 3 other variables, each of which is indexed from 0-45. It seems as though the array approach would be the most straightforward but I can't get it to work. So i have variables a_0,...,a_45,b_0,...,b_45,c_0,...,c_45 and i want to create d_i=a_i+b_i+c_i but I'm having some difficulty.
Attempt:
data test;
set test;
array d [0:45];
array a [0:45] a_0-a_45;
array b [0:45] b_0-b_45;
array c [0:45] c_0-c_45;
do i=0 to 45;
d[i]=a[i]+b[i]+c[i];
end;
run;
1) I can't seem to get the index from 0.
2) Whenever I run checks, the variables never add up in the intended way.
try changing array d defintion.
array d [0:45];
to
array d [0:45] d0-d45;
In case of array d [0:45] it creates d1 to d46 whereas in case of array d [0:45] d_0-d_45 you explicitly index from 0 to 45.
If you don't tell SAS what variable names to use for the array it will just create names using the array name and adding a numeric suffix. So when you wrote
array d [0:45];
You told it to create 46 variables named d1 to d46.
You could tell it what names to use.
array d [0:45] d_0 - d_45 ;
Also in the code you posted it doesn't really matter whether your index variable's value matches the numeric suffix on the variable names. So why not make it much simpler.
array a a_0-a_45;
array b b_0-b_45;
array c c_0-c_45;
array d d_0-d_45;
do i=1 to dim(a);
d(i)=a(i)+b(i)+c(i);
end;
You could also just number your variables starting with 1 instead of Zero and save a lot of headache.
I want to compare the pixel values of two images, which I have stored in arrays.
Suppose the arrays are A and B. I want to compare the elements one by one, and if A[l] == B[k], then I want to store the match as a key value-pair in a third array, C, like so: C[l] = k.
Since the arrays are naturally quite large, the solution needs to finish within a reasonable amount of time (minutes) on a Core 2 Duo system.
This seems to work in under a second for 1024*720 matrices:
A = randi(255,737280,1);
B = randi(255,737280,1);
C = zeros(size(A));
[b_vals, b_inds] = unique(B,'first');
for l = 1:numel(b_vals)
C(A == b_vals(l)) = b_inds(l);
end
First we find the unique values of B and the indices of the first occurrences of these values.
[b_vals, b_inds] = unique(B,'first');
We know that there can be no more than 256 unique values in a uint8 array, so we've reduced our loop from 1024*720 iterations to just 256 iterations.
We also know that for each occurrence of a particular value, say 209, in A, those locations in C will all have the same value: the location of the first occurrence of 209 in B, so we can set all of them at once. First we get locations of all of the occurrences of b_vals(l) in A:
A == b_vals(l)
then use that mask as a logical index into C.
C(A == b_vals(l))
All of these values will be equal to the corresponding index in B:
C(A == b_vals(l)) = b_inds(l);
Here is the updated code to consider all of the indices of a value in B (or at least as many as are necessary). If there are more occurrences of a value in A than in B, the indices wrap.
A = randi(255,737280,1);
B = randi(255,737280,1);
C = zeros(size(A));
b_vals = unique(B);
for l = 1:numel(b_vals)
b_inds = find(B==b_vals(l)); %// find the indices of each unique value in B
a_inds = find(A==b_vals(l)); %// find the indices of each unique value in A
%// in case the length of a_inds is greater than the length of b_inds
%// duplicate b_inds until it is larger (or equal)
b_inds = repmat(b_inds,[ceil(numel(a_inds)/numel(b_inds)),1]);
%// truncate b_inds to be the same length as a_inds (if necessary) and
%// put b_inds into the proper places in C
C(a_inds) = b_inds(1:numel(a_inds));
end
I haven't fully tested this code, but from my small samples it seems to work properly and on the full-size case, it only takes about twice as long as the previous code, or less than 2 seconds on my machine.
So, if I understand your question correctly, you want for each value of l=1:length(A) the (first) index k into B so that A(l) == B(k). Then:
C = arrayfun(#(val) find(B==val, 1, 'first'), A)
could give you your solution, as long as you're sure that every element will have a match. The above solution would fail otherwise, complaning that the function returned a non-scalar (because find would return [] if no match is found). You have two options:
Using a cell array to store the result instead of a numeric array. You would need to call arrayfun with 'UniformOutput', false at the end. Then, the values of A without matches in B would be those for which isempty(C{i}) is true.
Providing a default value for an index into A with no matches in B (e.g. 0 or NaN). I'm not sure about this one, but I think that you would need to add 'ErrorHandler', #(~,~) NaN to the arrayfun call. The error handler is a function that gets called when the function passed to arrayfun fails, and may either rethrow the error or compute a substitute value. Thus the #(~,~) NaN. I am not sure that it would work, however, since in this case the error is in arrayfun and not in the passed function, but you can try it.
If you have the images in arrays A & B
idx = A == B;
C = zeros(size(A));
C(idx) = A(idx);