confusion related to 'for' loop.

1 回表示 (過去 30 日間)
parag gupta
parag gupta 2019 年 3 月 20 日
回答済み: Steven Lord 2019 年 3 月 20 日
epsilon = 2
p = cell(1,8);
for i = 1:8
p{i} = epsilon
end
How to edit this code so that I can get p{1} = epsilon,p{2} = epsilon ^2 ,p{2} = epsilon ^3 .......
i.e i want p{1} = 2,p{2} = 4, p{3} =8.....
Thanks

採用された回答

madhan ravi
madhan ravi 2019 年 3 月 20 日
p = num2cell(2.^(1:8))
  1 件のコメント
madhan ravi
madhan ravi 2019 年 3 月 20 日
In your loop you just had to add
p{i} = epsilon^i
but you can straight away use the method in the answer.

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

その他の回答 (1 件)

Steven Lord
Steven Lord 2019 年 3 月 20 日
Do you need the elements in a cell array, or is having them in a regular vector sufficient?
epsilon = 2;
thepowers = 1:8;
p = epsilon.^thepowers
If you're preparing for epsilon being a vector or matrix in the future, you can still use this technique, taking advantage of implicit expansion which is a generalization of scalar expansion. It just gets a little more complicated for matrices or N-dimensional arrays.
epsilon = [1; 2; 3; 4];
thepowers = 1:8;
p2 = epsilon.^thepowers
For a matrix M, you want thepowers to be a 3-dimensional array.
epsilon = magic(4);
thepowers = reshape(1:8, 1, 1, []) % or
thepowers = reshape(1:8, [1 1 8])
p3 = epsilon.^thepowers

カテゴリ

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