How to replace for loop ?

3 ビュー (過去 30 日間)
Ammy
Ammy 2022 年 3 月 2 日
編集済み: Ammy 2022 年 3 月 15 日
function [a] =my_function(b,c)
a = b+c;
end
for i=1:10
a = my_function(a,c)
end
How to replace for loop ?
  1 件のコメント
Torsten
Torsten 2022 年 3 月 2 日
a=a+10*c

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

回答 (1 件)

Fangjun Jiang
Fangjun Jiang 2022 年 3 月 2 日
This is not really a "vectorization" problem. "Vectorization" refers to performing a task on a vector as a whole, rather than performing the task on each element of the vector, which needs to be done multiple times to finish the overall task. The number of repitition depends on the size of the vector or matrix.
You have a user-defined function. You need to repeat it 10 times. What about 100 times? Does the number of repitition has anything to do with the size of "a"?
arrayfun() could be useful if the user-defined function does not support vector/matrix but you want it perform on a vector/matrix.
One thing seems to be special is that the output of your user-defined function is feedback as one input of the function in the next iteration. This seems to fit in the case of a recursive function. Search for "recursive function" and learn how to write it. You might be able to achieve your goal with a recursive function without a for-loop.
  1 件のコメント
Ammy
Ammy 2022 年 3 月 3 日
@Fangjun Jiang thank you very much for such a brief and valuable explanation

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

Community Treasure Hunt

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

Start Hunting!

Translated by