how automatically label multiple outputs in the loop?

hi how automatically label multiple outputs in the loop? I do not know it is possible or not... may be it is very basic...
I mean basically
for i=1:3
x=i^2
end
here the outputs
x =
1
x =
4
x =
9
I want to label those x st
x(1)=1
x(2)=4
x(3)=9

回答 (2 件)

Dr. Seis
Dr. Seis 2013 年 5 月 20 日

1 投票

If you know how many elements in x there will be (3 in your example), then it is best to initialize the output:
x = zeros(3,1); % 3 rows and 1 column of zeros
Then perform your calculations:
for i = 1 : 3
x(i) = i^2;
end

4 件のコメント

frwmetric
frwmetric 2013 年 5 月 20 日
I don't know how many elements in x... actually this is my another problem...
Dr. Seis
Dr. Seis 2013 年 5 月 20 日
編集済み: Dr. Seis 2013 年 5 月 20 日
You do not "need" to initialize... Matlab might complain that the size of x appears to increase during each loop, but it should still work without initializing. If x gets very large, then you can see significant speed-up by initializing.
Image Analyst
Image Analyst 2013 年 5 月 20 日
You can initialize to the max you ever expect to see, and then truncate later once you know the number of elements you actually need:
% Preallocate space for as many as 3 million elements.
x = zeros(3000000,1); % 3 million rows and 1 column of zeros
Then perform your calculations:
for i = 1 : 2000000 % 2 million.
x(i) = i^2;
end
% Truncate to known length of 2 million elements.
x = x(1:2000000);
Iain
Iain 2013 年 5 月 20 日
You could also do the loop in the opposite direction. High indices to low indices.

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

José-Luis
José-Luis 2013 年 5 月 20 日
編集済み: José-Luis 2013 年 5 月 20 日

0 投票

x = 1:3; %Creating a vector of values
your_result = x.^2; %squaring element by element
x(1)
x(2)
x(3)
I would recommend you read the Getting started part of the documentation.

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

質問済み:

2013 年 5 月 20 日

Community Treasure Hunt

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

Start Hunting!

Translated by