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!