Splitting a matrix in vectors and combination of vectors

6 visualizzazioni (ultimi 30 giorni)
Hello!
I would like to split the Matrix Z into vectors(?), so i can combine these vectors.
First column of Z: Row indices of matrix A with maximum value. Second column of Z: Column indices of matrix A with maximum value. Thus Z gives me the positions of the maximum values of each row of matrix A. If A contains rows filled with 0 (so the maximum value would be 0), Z depicts it with a 0. Works so far.
A = [2 2 0 1; 0 0 0 0; 0 0 0 0; 2 0 0 2]
Z = 1 1
1 2
2 0
3 0
4 1
4 4
Now i want to save all column indices which have the same row index in a separate vector v(row_index)=[column indices]:
v1=[1 2], v2=[0], v3=[0], v4=[1 4]
In the second step i want to combine these vector in the order v1-v2-v3-v4 to get all possible combinations:
Output_Matrix = [1 0 0 1; 1 0 0 4; 2 0 0 1; 2 0 0 4] -> "Possible paths with the max sum"
How can i do these two steps?
Thanks in advance!

Risposta accettata

Rik
Rik il 9 Mar 2022
Note that this method results in a different sort from what you describe. You could use sortrows if the order is important to you.
Z =[ 1 1
1 2
2 0
3 0
4 1
4 4];
c=cell(max(Z(:,1)),1);
for dim=1:numel(c)
% Select all indices in Z for this element
data=Z(Z(:,1)==dim,2);
% Make sure the 1 is at the dim index of this vector.
ind=circshift(1:numel(c),dim-1);
% Reshape the data to an ND vector.
tmp=permute(data,ind);
% Store in the cell.
c{dim}=tmp;
end
% Use ndgrid to create all combinations.
[c{:}]=ndgrid(c{:});
% Reshape each element back to a column vector.
for dim=1:numel(c)
c{dim}=c{dim}(:);
end
% Concatenate back to a single matrix.
Output_Matrix = horzcat(c{:})
Output_Matrix = 4×4
1 0 0 1 2 0 0 1 1 0 0 4 2 0 0 4
  2 Commenti
L. Edwin M.
L. Edwin M. il 9 Mar 2022
Thank you a lot, perfect!!! Could you explain why i need these two lines or what they do? :
% Make sure the 1 is at the dim index of this vector.
ind=circshift(1:numel(c),dim-1);
% Reshape the data to an ND vector.
tmp=permute(data,ind);
I tried it without them and it works too.
Rik
Rik il 9 Mar 2022
At first I had a different idea, which required the first input to be Nx1x1x1, the second to be 1xMx1x1, etc. That is what these two lines do. I forgot about the fact that ndgrid will happily accept vector inputs of any dimension and return the same output.

Accedi per commentare.

Più risposte (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by