Insert rows in a matrix

3 ビュー (過去 30 日間)
Ionut  Anghel
Ionut Anghel 2015 年 6 月 24 日
コメント済み: David Verrelli 2018 年 3 月 27 日
Hi, I have the following problem: matrix
AA=[NaN 1 2 3 4 5
NaN 10 20 30 40 50
...............
NaN 1E8 2E8 3E8 4E8 5E8 ];
There is possible to insert every 10 row the following row:
[NaN NaN 99 Nan 77 NaN];
without a loop?
Thank you

採用された回答

Guillaume
Guillaume 2015 年 6 月 24 日
One way of doing this:
%work out how to split AA
rowdist = ones(1, ceil(size(AA, 1) / 10)) * 10;
rowdist(end) = 10 + mod(size(AA, 1), -10);
%do the splitting and transpose into a row
splitAA = mat2cell(AA, rowdist, size(AA, 2))';
%add another row with the data to insert
splitAA(2, :) = {[NaN NaN 99 NaN 77 NaN]};
%avoid insertion of the new row at the end if the height
%of the matrix is not a multiple of ten
if mod(size(AA, 1), 10)
splitAA{2, end} = [];
end
%join it all together
newAA = vertcat(splitAA{:})
  1 件のコメント
Ionut  Anghel
Ionut Anghel 2015 年 6 月 24 日
Very nice method! Thank you.

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

その他の回答 (1 件)

Anthony Poulin
Anthony Poulin 2015 年 6 月 24 日
編集済み: Anthony Poulin 2015 年 6 月 24 日
You can try something like this (with B = [NaN NaN 99 Nan 77 NaN]):
for i=10:10:100
AA = [AA(1:i, 1:end); B; AA(i+1:end,1:end)];
end
(100 is an arbitrary value)
  4 件のコメント
Anthony Poulin
Anthony Poulin 2015 年 6 月 24 日
Or just replacing "i" by "i + i/10 -1".
David Verrelli
David Verrelli 2018 年 3 月 27 日
Or run the loop 'backwards', as in for i=100:-10:10 (although 100 might not be the correct terminal value for your case, as already noted). Even though the matrix is still resized at each step, at least this way the subsequent changes aren't affected by previous steps.
BTW, "1:end" can just be replaced with ":" alone.

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

カテゴリ

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