Append rows at the end of matrix for loop

22 ビュー (過去 30 日間)
Rachel Ramirez
Rachel Ramirez 2021 年 1 月 7 日
コメント済み: Rik 2021 年 1 月 24 日
Hello,
I need some help with a for loop. I have matrix A (5x2) and matrix B (3x2). (See image) I want to have 3 different combinations (3 new matrices size 6x2) and for each combination add one row from matrix B at the end of matrix A. How can I approach this?
  1 件のコメント
Rik
Rik 2021 年 1 月 24 日
Just in case you try to edit away your question I made a capture.
Why do you think your question is not clear? Why not improve it instead of flagging it?

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

回答 (2 件)

Jan
Jan 2021 年 1 月 7 日
編集済み: Jan 2021 年 1 月 7 日
A = rand(5, 2);
B = rand(3, 2);
Result = cell(1, 3);
for k = 1:3
Result{k} = [A; B(k, :)];
end

Robert Rasche
Robert Rasche 2021 年 1 月 7 日
It depends on the format/order in which the new matrices shall be output. Do you want them as a collection (cell) or one after another?
In any case, it should be pretty simple, because you just have iterate through the height-dimension of B:
C = cell(size(B, 1), 1); % in case a collection is needed (*)
for i in 1:size(B, 1)
M = [A; B(i, :)];
C{i} = M; % (*)
end
or something.
  2 件のコメント
Rachel Ramirez
Rachel Ramirez 2021 年 1 月 7 日
Thank you for your reply.umm haven't used cell before, will look into what it's for.
What I wanted to output it's something like the following. 3 matrices. each of the matrices has the 5x2 values from matrix A and at the end 1/3 rows from Matrix B.
Also another thing, I'm using an example of an specifc size but since my matrix would vary i would rather not specify a size in specifc. is that possible?
Robert Rasche
Robert Rasche 2021 年 1 月 8 日
This is what that code will do and it will also work with different sizes - as long as A and B have the same number of columns of course.
The crucial part in both Jan's and my answer is where it says
= [A; B(i,:)];
  • snip out a part of B, the i-th line (via ...(i, :)) and then
  • stich it to your A by vertical concatenation (via [... ; ...])
If you want there to always be 3 result matrices instead of as many as B has rows, then the loop bounds and snipping-part would have to be ajusted, but i don't think it is what you want.

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

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by