I would like to separate a matrix into different matrices based on a cycle of the first values
조회 수: 4 (최근 30일)
이전 댓글 표시
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
Bruno Luong
2018년 11월 9일
Please post your for-loop because the description "cycle of the first values" is unclear.
채택된 답변
Bruno Luong
2018년 11월 9일
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
추가 답변 (1개)
Luna
2018년 11월 9일
편집: Luna
2018년 11월 9일
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
Jan
2018년 11월 9일
편집: Jan
2018년 11월 9일
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
2018년 11월 9일
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);
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!