Splitting a matrix based on certain values in the rows

18 ビュー (過去 30 日間)
Mr. 206
Mr. 206 2019 年 2 月 19 日
コメント済み: Jos (10584) 2019 年 2 月 20 日
I have a matrix A like this:
A = [911 911;
0 2;
8 5;
7 3;
911 911;
5 3;
1 6;
6 7;
911 911;
3 5;
8 4];
I want to split the matrix A into three matrices (A1,A2,A3) based on the row values 911 like this:
A1 = [0 2; 8 5; 7 3];
A2 = [5 3; 1 6; 6 7];
A3 = [3 5; 8 4];
I need to do this thing inside a for loop which will give the spitted matrix one after another.
  3 件のコメント
Mr. 206
Mr. 206 2019 年 2 月 19 日
This is just a dummy. It can be A, B,C or any other name.
Jan
Jan 2019 年 2 月 19 日
@Atta: A,B,C, ... suffers from exactly the same problems as A1, A2, A3, ... With using a cell array and and index, the code is fast and flexibel. You can e.g. simply run it for 12'781'986 rows without getting mad while typing the code with manually hidden names of variables.

サインインしてコメントする。

採用された回答

Stephen23
Stephen23 2019 年 2 月 19 日
編集済み: Stephen23 2019 年 2 月 19 日
No loop required:
>> idx = cumsum(all(A==911,2));
>> row = 1:numel(idx);
>> fun = @(r){A(r(2:end),:)};
>> C = accumarray(idx,row(:),[],fun);
>> C{:}
ans =
0 2
8 5
7 3
ans =
5 3
1 6
6 7
ans =
3 5
8 4
  4 件のコメント
Mr. 206
Mr. 206 2019 年 2 月 20 日
編集済み: Mr. 206 2019 年 2 月 20 日
Thanks, I got it.
I just need another help, I have another 5 by 6 matrix (say D). I want to pad the matrices C{1}, C{2} and C{3} by some random number, so that the row numbers are equal.
For example, C{3} has 2 rows, so i need to put three e.g 911911 value at the bottom to make the row number equal to matrix D (5 by 6)
Jos (10584)
Jos (10584) 2019 年 2 月 20 日
% Pad each cell with rows of 911,
% so that it has the same number of rows as D
% using CELLFUN with an anonymous padding function using REPMAT
C2 = cellfun(@(m) [m ; repmat(911, size(D,1)-size(m,1),size(m,2))], C)

サインインしてコメントする。

その他の回答 (1 件)

Jan
Jan 2019 年 2 月 19 日
編集済み: Jan 2019 年 2 月 19 日
A = [911 911;
0 2;
8 5;
7 3;
911 911;
5 3;
1 6;
6 7;
911 911;
3 5;
8 4];
index = [find(A(:, 1) == 911); size(A, 1) + 1];
n = numel(index) - 1;
Result = cell(1, n);
for k = 1:n
Result{k} = A(index(k):index(k+1)-1, :); % [EDITED]
end
  2 件のコメント
Mr. 206
Mr. 206 2019 年 2 月 19 日
It's throwing an error, like "error: A(I,J): row index out of bounds; value 12 out of bound 11"
Jan
Jan 2019 年 2 月 19 日
@Atta: Yes, I had a typo in my code. It is fixed now. Sometimes I expect the readers to fix bugs, when they are not too hard.
The result is a cell array and you access it as Result{1}. This is much smarter than hiding an index in the name of a variable.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by