Add variables calculated in a for loop into an array

25 ビュー (過去 30 日間)
Greg Dunphy
Greg Dunphy 2021 年 7 月 28 日
コメント済み: Stephen23 2021 年 7 月 29 日
I am trying to run a for loop where I call a 'caculate' function on each element of an array, and then save each new calculated variable to a new array that has 1 column and 9 rows.
% numbers is an array of 1 column by 9 rows of individual numbers
newNums = cell(9,1)
for num = numbers
newNum = calculate(num);
newNums([num]) = newNum;
end
Apologies for my code I am brand new to matlab and usually use Python!
  1 件のコメント
Stephen23
Stephen23 2021 年 7 月 28 日
編集済み: Stephen23 2021 年 7 月 28 日
Why are you using a cell array to store (what are apparently) numeric scalars?
A simple numeric vector would be more effiicient and probably much easier to process later.
Note that FOR operates over the columns of the input array, which means that following your description the loop will iterate exactly once (and num will be that entire column vector). I doubt that is very useful for you.

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

採用された回答

Stephen23
Stephen23 2021 年 7 月 28 日
編集済み: Stephen23 2021 年 7 月 28 日
I suspect that you need something like this:
nml = numel(numbers);
out = nan(nml,1);
for k = 1:nml
out(k) = calculate(nummbers(k));
end
Tip: learn the basics of MATLAB by doing these tutorials:
  1 件のコメント
Stephen23
Stephen23 2021 年 7 月 29 日
@Greg Dunphy: please show the entire error message (this means all of the red text), and the code that you tried.

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

その他の回答 (1 件)

Cris LaPierre
Cris LaPierre 2021 年 7 月 28 日
It looks like you could use some general help on how to write a for loop. Check out the examples on the for documetnation page. Another great place to practice interactively is Ch 13 of MATLAB Onramp.

カテゴリ

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