What are the differences between these array definitions in MATLAB? - matlab

I am trying to understand the differences between these array definitions:
abc=[ 0 0 0 0 0 0]
and
abc=[0;0;0;0;0;0]
In C, first definition is
int abc[]={0,0,0,0,0,0};
second definition is
int [6][1]= {{0},{0},{0},{0},{0},{0}};
Am I correct about that?

abc = [1 2 3 4]
Is a "row vector".
abc = [1 2; 3 4]
Is a 2x2 matrix, because semicolons inside brackets separate rows.
abc = [1; 2; 3; 4]
Is a 4x1 matrix, aka "column vector". It's a special case of a matrix, really. You can also get it by transposing the corresponding row vector:
abc = [1 2 3 4]'
(note the quote at the end - this is the transpose)
P.S.: Yes, your interpretation to C is correct in this case.

Related

Generate a enumeration matrix in MATLAB [duplicate]

I would like to generate all the possible combinations of the elements of a given number of vectors.
For example, for [1 2], [1 2] and [4 5] I want to generate the elements:
[1 1 4; 1 1 5; 1 2 4; 1 2 5; 2 1 4; 2 1 5; 2 2 4; 2 2 5]
The problem is that I don't know the number of vectors for which I need to calculate the combinations. There might be 3 as in this case, or there may be 10, and I need a generalization. Can you please help me to this in MATLAB? Is there already a predefined function that can do this task?
Consider this solution using the NDGRID function:
sets = {[1 2], [1 2], [4 5]};
[x y z] = ndgrid(sets{:});
cartProd = [x(:) y(:) z(:)];
cartProd =
1 1 4
2 1 4
1 2 4
2 2 4
1 1 5
2 1 5
1 2 5
2 2 5
Or if you want a general solution for any number of sets (without having to create the variables manually), use this function definition:
function result = cartesianProduct(sets)
c = cell(1, numel(sets));
[c{:}] = ndgrid( sets{:} );
result = cell2mat( cellfun(#(v)v(:), c, 'UniformOutput',false) );
end
Note that if you prefer, you can sort the results:
cartProd = sortrows(cartProd, 1:numel(sets));
Also, the code above does not check if the sets have no duplicate values (ex: {[1 1] [1 2] [4 5]}). Add this one line if you want to:
sets = cellfun(#unique, sets, 'UniformOutput',false);
Try ALLCOMB function at FileExchange.
If you store you vectors in a cell array, you can run it like this:
a = {[1 2], [1 2], [4 5]};
allcomb(a{:})
ans =
1 1 4
1 1 5
1 2 4
1 2 5
2 1 4
2 1 5
2 2 4
2 2 5
This late answers provides two additional solutions, where the second is the solution (in my opinion) and an improvement on Amro's answer solution with ndgrid by applying MATLAB's powerful comma-separated lists instead of cell arrays for high performance,
If you have the Neural Network Toolbox: use combvec
If you do not have the toolbox, as is usually the case: below is another way to generalize the Cartesian product for any number of sets.
Just as Amro did in his answer, the comma-separated lists syntax (v{:}) supplies both the inputs and outputs of ndgrid. The difference (fourth line) is that it avoids cellfun and cell2mat by applying comma-separated lists, again, now as the inputs to cat:
N = numel(a);
v = cell(N,1);
[v{:}] = ndgrid(a{:});
res = reshape(cat(N+1,v{:}),[],N);
The use of cat and reshape cuts execution time almost in half. This approach was demonstrated in my answer to an different question, and more formally by Luis Mendo.
we can also use the 'combvec' instruction in matlab
no_inp=3 % number of inputs we want...in this case we have 3 inputs
a=[1 2 3]
b=[1 2 3]
c=[1 2 3]
pre_final=combvec(c,b,a)';
final=zeros(size(pre_final));
for i=1:no_inp
final(:,i)=pre_final(:,no_inp-i+1);
end
final
Hope it helps.
Good luck.

Create Non Zero elements of Matrix in vector form in Matlab

I have a Matrix of size M by N in which each row has some zero entries. I want to create M row vectors such that each of the vector contains the non zero elements of each row. For example if I have the following Matrix
A=[0 0 0 5;0 0 4 6;0 1 2 3;9 10 2 3]
I want four different row vectors of the following form
[5]
[4 6]
[1 2 3]
[9 10 2 3]
This can be done with accumarray using an anonymous function as fourth input argument. To make sure that the results are in the same order as in A, the grouping values used as first input should be sorted. This requires using (a linearized version of) A transposed as second input.
ind = repmat((1:size(A,2)).',1,size(A,2)).';
B = A.';
result = accumarray(ind(:), B(:), [], #(x){nonzeros(x).'});
With A = [0 0 0 5; 0 0 4 6; 0 1 2 3; 9 10 2 3]; this gives
result{1} =
5
result{2} =
4 6
result{3} =
1 2 3
result{4} =
9 10 2 3
Since Matlab doesn't support non-rectangular double arrays, you'll want to settle on a cell array. One quick way to get the desired output is to combine arrayfun with logical indexing:
nonZeroVectors = arrayfun(#(k) A(k,A(k,:)~=0),1:size(A,1),'UniformOutput',false);
I used the ('UniformOutput',false) name-value pair for the reasons indicated in the documentation (I'll note that the pair ('uni',0) also works, but I prefer verbosity). This input produces a cell array with the entries
>> nonZerosVectors{:}
ans =
5
ans =
4 6
ans =
1 2 3
ans =
9 10 2 3

matlab indexing with multiple condition

I can't figure out how to create a vector based on condition on more than one other vectors. I have three vectors and I need values of one vector if values on other vectors comply to condition.
As an example below I would like to choose values from vector a if values on vector b==2 and values on vector c==0 obviously I expect [2 4]
a = [1 2 3 4 5 6 7 8 9 10];
b = [1 2 1 2 1 2 1 2 1 2];
c = [0 0 0 0 0 1 1 1 1 1]
I thought something like:
d = a(b==2) & a(c==0)
but I have d = 1 1 1 1 1 not sure why.
It seems to be basic problem but I can find solution for it.
In your case you can consider using a(b==2 & c==0)
Use ismember to find the matching indices along the rows after concatenating b and c and then index to a.
Code
a(ismember([b;c]',[2 0],'rows'))
Output
ans =
2
4
You may use bsxfun too for the same result -
a(all(bsxfun(#eq,[b;c],[2 0]'),1))
Or you may just tweak your method to get the correct result -
a(b==2 & c==0)

How to use find function for different value at each row of a matrix?

suppose I have values need_find = [1 3 4] and a matrix A in the size of 3xK. I want to find the values of need_find on its corresponding row of A. How can I apply vectorized solution in matlab instead of iterate over each row?
For detailed example as expected;
A = [1 3 4; 1 3 5; 3 4 5];
my_method_do_what_I_want(A,need_find);
The method returns
ans = [1;2;2]
% so I find the index of each element of need_find at corresponding row at A
Long story short :seach 1 at row 1, search 3 at row2, search 4 at row3
Here's one way:
A = [1 3 4; 1 3 5; 3 4 5];
need_find = [1 3 4]
[~,idx] = find(bsxfun(#eq,A,need_find(:)))
which returns
idx =
1
2
2
This simple one-liner won't work if you have repeated values in the rows of A or if there are no matches at all, but I can only go by your example...

Matlab Extend Diagonal by one

Suppose I have a matrix A, and I'd like to get the matrix [A 0; 0 1]. Is there a built function to do this?
So if my matrix is [2 3; 1 4], I'd get back [2 3 0; 1 4 0; 0 0 1]
The easiest way is:
newA = A;
newA(end+1,end+1) = 1;
This works because you can index outside an array for assignments, because end indicates the last element (here in row and column), and because Matlab pads with zeros when you grow an array. If you just want to grow A, you can even skip the creation of newA, of course.
I always use matrix concatenation for problems like this
So for your example:
A = [2 3; 1 4]
A = [A A(:,1)*0; A(1,:)*0 1]
produces
A =
2 3 0
1 4 0
0 0 1
The nice thing about this trick is that its very flexible and you can do all sorts of tranformations
very easily. For example
A = [2 3; 1 4]
A = [1 A(1,:)*0; A(:,1)*0 A]
produces
A =
1 0 0
0 2 3
0 1 4