split matrix in diffrent sizes matrixes according to indicies vector

2 ビュー (過去 30 日間)
christine schaer
christine schaer 2019 年 9 月 25 日
コメント済み: christine schaer 2019 年 9 月 26 日
I have a matrix A (7x2) and a vector B. B represents the row indicies, where i want the matrix A to be sprlit.
e.g.
A = [2 6; 4 3; 3 3; 2 8; 9 1; 3 4; 7 5] B=[2; 3; 6]
output should be
A1 = [2 6; 4 3]
A2 = [3 3]
A3 = [2 8; 9 1; 3 4]
A4 = [7 5]
Do you have an idea how it could be done?
Thank you for help.

採用された回答

Stephen23
Stephen23 2019 年 9 月 25 日
編集済み: Stephen23 2019 年 9 月 25 日
Do NOT create numbered variables. Indexing is simpler and much more efficient.
You can use mat2cell to split the matrix up into a cell array:
>> R = diff([0;B;size(A,1)]);
>> C = mat2cell(A,R,2);
>> C{:}
ans =
2 6
4 3
ans =
3 3
ans =
2 8
9 1
3 4
ans =
7 5
and then you can trivially access the contents of that cell array using indexing:
E.g.:
>> C{2}
ans =
3 3
>> C{3}
ans =
2 8
9 1
3 4
  3 件のコメント
Stephen23
Stephen23 2019 年 9 月 26 日
編集済み: Stephen23 2019 年 9 月 26 日
"I want to add a third row to each cell ..."
This is confusing, because in your example you are adding a third column, not a row. Remember that matrices are defined by rows*columns, and this is how MATLAB indexing works too: (rows,columns,pages,...)
In any case, you can simply use a loop, e.g.:
for k = 1:numel(C)
C{k}(:,3) = cumsum(C{k}(:,2));
end
Giving:
>> C{:}
ans =
2 6 6
4 3 9
ans =
3 3 3
ans =
2 8 8
9 1 9
3 4 13
ans =
7 5 5
Or, if you really want to use cellfun, something like this:
>> F = @(m)[m,cumsum(m(:,2))];
>> C = cellfun(F,C,'uni',0);
>> C{:}
ans =
2 6 6
4 3 9
ans =
3 3 3
ans =
2 8 8
9 1 9
3 4 13
ans =
7 5 5
christine schaer
christine schaer 2019 年 9 月 26 日
thank you.. i meant columne sorry

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

その他の回答 (1 件)

the cyclist
the cyclist 2019 年 9 月 25 日
Stephen's solution is better, but I thought I would post this for loop version, which might be a bit clearer to you on what is happening:
A = [2 6;
4 3;
3 3;
2 8;
9 1;
3 4;
7 5];
B=[2; 3; 6];
C = [0; B; size(A,1)];
for nj = 1:numel(C)-1
An{nj} = A(C(nj)+1:C(nj+1),:);
end
I would also advocate using cell arrays rather than dynamically named variables.

カテゴリ

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