Reputation: 79
Is there a function that can repeat a segment of code for a given number of times?
for example:
t= 0;
while (t< 10)
if x==2
x=1
else
x=3;
end
end
How can i rewrite this function using another function ?
Upvotes: 0
Views: 4959
Reputation: 21563
Matlab automatically 'repeats' the code for you if you put it in a vector format:
x_vector = round(2*rand(10,1)) %Your x input
idx = (x_vector==2)
x_vector(idx) = 1;
x_vector(~idx) = 3;
Upvotes: 1
Reputation: 8391
Or, if the code executed in one iteration is independent on the results of other iterations, you can use arrayfun
or cellfun
.
For instance
fun = @(x) disp(['hello ' , num2str(x)]);
arrayfun(fun,1:5);
returns
hello 1
hello 2
hello 3
hello 4
hello 5
Personally I do like these constructs because I find them very expressive just as std::for_each
in C++.
Nonetheless, they have proven to be slower than their naive-loop counterparts which get JITed away by Matlab (there are several Q/A about this issue here on SO).
Upvotes: 2
Reputation: 4888
A recursive function can do this for you (assuming you can't use: for,while,repeat).
http://www.matrixlab-examples.com/recursion.html
Upvotes: 4