Use function inside a loop that gives the function's output multiple times - How to avoid overwriting output?

Hello everyone,
I am using a function that i have wrtitten inside a for loop..
i.e. for i=1:100
S=function_example(S,etc)
end
The output of one step is input for the function in the next step and so on...
I know that i can use indexing and an array S to store everything there (e.g S(i+1), S(i))... However I am looking for a more sophisticated way!!
Is there one ?? I need these looped function outputs for plotting my results...

 采纳的回答

If you want to plot it, you need the array, right? What else do you have in mind then?

5 个评论

Thanks a lot for your response Yongjian!
I was thinking if there is something where i could avoid indexing??
If you just want to avoid indexing, then something like this:
anArray = [];
S = 0; % Need to initialize S
for i=1:100
S=function_example(S,etc);
anArray(end+1) = S;
end
"If you just want to avoid indexing, then something like this"
will be less efficient and just as complex as indexing.
Thanks a lot for your response. I will probably use an array eventually. I was trying to avoid using all the i+1 etc cause sometimes it can be confusing for someone that reads my code to understand but i will probably stick to it as it is the only way to go.
" I was trying to avoid using all the i+1 etc cause sometimes it can be confusing for someone that reads my code"
Indexing is a basic MATLAB technique for accessing data in arrays.
You can assume that in general someone reading MATLAB code will not be confused by a simple i+1 index.

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by