Say I have a 3x2 matrix (A) that ranges from the numbers 1 through 5. The 3 rows equals 3 different sets of numbers. I have to use a loop to populate a vector (B) that is the size 3x1 (3 for each set). This vector will populate with the first number in each set (every number in the first column).
So if the matrix A =
2 3
1 1
5 4
the vector B should be
2
1
5
How would you use the loop function to do that?

 採用された回答

Moe_2015
Moe_2015 2016 年 2 月 16 日
編集済み: Moe_2015 2016 年 2 月 16 日

0 投票

If you really need to use a for loop, this is how you could do it.
for i=1:size(A,1)
B(i,1)=A(i,1);
end
However, a more efficient way would be:
B=A(:,1)

4 件のコメント

lauuser1
lauuser1 2016 年 2 月 16 日
These both work exactly how I want it, however when I suppress B in the loop function it ceases to show B at all. When I remove the suppression, it shows every step of populating B. This doesn't really affect my code, but would there be a way to fix that?
Image Analyst
Image Analyst 2016 年 2 月 16 日
Fix what? What does suppression mean to you? You mean having the value of B echo to the command window if you leave off the semicolon? If so, I'm still not sure what you want, or don't want, to see.
lauuser1
lauuser1 2016 年 2 月 16 日
What I am trying to fix is that I just want the final result of B rather than it echoing. I would like to see B in my command window as just one single fully populated 3x1 vector with no values of 0.
Image Analyst
Image Analyst 2016 年 2 月 16 日
Put B by itself after the loop to have it echo only the final B
for i=1:size(A,1)
B(i,1)=A(i,1); % Semicolon to suppress echo to command window.
end
% Print B to command window:
B

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2016 年 2 月 16 日

コメント済み:

2016 年 2 月 16 日

Community Treasure Hunt

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

Start Hunting!

Translated by