I would like to separate a matrix into different matrices based on a cycle of the first values
4 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Adolf Krige
il 9 Nov 2018
Commentato: Adolf Krige
il 9 Nov 2018
i.e. [1 2 3 1 2 4; 1 1 1 2 2 2]=>[1 2 3; 1 1 1] and [1 2 4; 2 2 2] i can do it with a for loop looking for values that are smaller than the previous, but I feel there must be a faster way
2 Commenti
Bruno Luong
il 9 Nov 2018
Please post your for-loop because the description "cycle of the first values" is unclear.
Risposta accettata
Bruno Luong
il 9 Nov 2018
A=[1 2 3 1 2 4; 1 1 1 2 2 2];
lgt = diff(find([true,diff(A(1,:),1,2)<0,true]));
C = mat2cell(A,size(A,1),lgt);
Result:
C{:}
ans =
1 2 3
1 1 1
ans =
1 2 4
2 2 2
Più risposte (1)
Luna
il 9 Nov 2018
Modificato: Luna
il 9 Nov 2018
Hi Adolf,
As far as I understand from your question. The cycle means that if your data is smaller than the previous data according to your first row, you want to divide your matrix into small matrices according to those cycles.
here is a piece of code executes what you want:
A = [1 2 3 1 2 4 1 2 5; 1 1 1 2 2 2 3 3 3];
indexedElementNumber = [1; find((diff(A') < 0))+1];
for i = 1:numel(indexedElementNumber)-1
eval([ 'X_',sprintf('%d',i), ' = A(:,indexedElementNumber(i):indexedElementNumber(i+1)-1)' ]);
end
i = i+1;
eval([ 'X_',sprintf('%d',i), ' = A(:,indexedElementNumber(i):end)' ]);
3 Commenti
Jan
il 9 Nov 2018
Modificato: Jan
il 9 Nov 2018
This is a very bad idea. See Why and how to avoid eval . Creating variables dynamically has many severe drawbacks. Use an array instead:
A = [1 2 3 1 2 4 1 2 5; 1 1 1 2 2 2 3 3 3];
index = [1, find((diff(A(1, :)) < 0))+1];
X = cell(1, numel(index));
for i = 1:numel(index) - 1
X{i} = A(:, index(i):index(i+1) - 1);
end
X{i} = A(:, index(end):end);
In "i=i+1" outside the loop you rely on the observation, that the loop counter has the maximum value after the loop. But this is not documented as far as I know.
Luna
il 9 Nov 2018
Hi Jan,
Yes, you are absolutely correct. Actually I know why we should avoid eval and I never use it in my codes normally. But I thought he might need the variables in his workspace.
I have tried your code, the max value of the for loop is 2 but we have 3 cycles so yours will get the last cycle which starts with [1 2 5; 3 3 3] and replaces it with the 2nd cycle. So the 3rd element of cell array X is always empty.
I replaced the same code with cell array instead of eval.
A = [1 2 3 1 2 4 1 2 5; 1 1 1 2 2 2 3 3 3];
indexedElementNumber = [1; find((diff(A') < 0))+1];
X = cell(1,numel(indexedElementNumber));
for i = 1:numel(indexedElementNumber)-1
X{i} = A(:,indexedElementNumber(i):indexedElementNumber(i+1)-1);
end
i = i+1;
X{i} = A(:,indexedElementNumber(i):end);
Vedere anche
Categorie
Scopri di più su Matrix Indexing in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!