Using loop to create multiple variables

4 ビュー (過去 30 日間)
Carson Wallace
Carson Wallace 2020 年 10 月 13 日
コメント済み: Carson Wallace 2020 年 10 月 13 日
Say I wanted to create 16 variables: x1, x2, ... x16. Each x variable is equal to b1, b2, ... b16 * some scalar A. Could I use a for loop to accomplish this task? I was thinking along the lines of:
for i = 1:1:16
x_i = b_i * A
i = i+1
end
But this won't work.
  1 件のコメント
Stephen23
Stephen23 2020 年 10 月 13 日
編集済み: Stephen23 2020 年 10 月 13 日
"Say I wanted to create 16 variables: x1, x2, ... x16. Each x variable is equal to b1, b2, ... b16 * some scalar A."
That would not be a very good use of MATLAB. The MATLAB documentation states "A frequent use of the eval function is to create sets of variables such as A1, A2, ..., An, but this approach does not use the array processing power of MATLAB and is not recommended. The preferred method is to store related data in a single array."
Storing data in one array makes it easy to write simple and efficient MATLAB code. Is there are a particular reason why you want to make your task complex and inefficient? What are you actually trying to achieve here? What is the goal?

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

採用された回答

Sudhakar Shinde
Sudhakar Shinde 2020 年 10 月 13 日
you can try this:
%b is a vector contains values from 1,2,3....to 16.
b = 1:16;
A=2; % A is a scalr whose value is 2
for i = 1:1:16
x(i) = b(i) * A;
i = i+1;
end
  2 件のコメント
Stephen23
Stephen23 2020 年 10 月 13 日
編集済み: Stephen23 2020 年 10 月 13 日
Or the MATLAB way:
x = A.*b;
Carson Wallace
Carson Wallace 2020 年 10 月 13 日
Thank you. This answers my question.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by