Vectorize loop with function containing randoms
Info
Diese Frage ist geschlossen. Öffnen Sie sie erneut, um sie zu bearbeiten oder zu beantworten.
Ältere Kommentare anzeigen
Hello,
I would like to know if there is any way to vectorize this:
ds=zeros(1,max);
for i=1:max
ds(i)=containsRandoms(p1);
end
p1 is always a fixed scalar, I just want to execute the function many times to fill ds. The function I'm calling inside the loop contains randoms and many other calculations, so it will produce a different result each time.
I was trying something like
ds(1:max)=containsRandoms(p1);
but it is only executing containsRandoms once, and therefore ds is filled with the same value repeated max times.
Thanks in advance.
Antworten (3)
Peter
am 14 Okt. 2011
1 Stimme
You'd have to vectorize containsRandoms, not just the assignment to ds.
4 Kommentare
sforza
am 14 Okt. 2011
Fangjun Jiang
am 14 Okt. 2011
The for-loop in new version of MATLAB has been very efficient. Sometimes it's even faster then no-loop approach.
Sean de Wolski
am 14 Okt. 2011
Yes. Avoid arrayfun. A for-loop is easier to understand and probably faster, especially in older versions.
sforza
am 14 Okt. 2011
Fangjun Jiang
am 14 Okt. 2011
First, don't use max as a variable name as max() is a popular function.
Second, Are you looking at: ds=rand(5,3) for example?
Or:
a=magic(3);
b=arrayfun(@containsRandoms,a)
Assume your function containsRandoms() is something like this:
function out=containsRandoms(in)
out=in+rand;
5 Kommentare
sforza
am 14 Okt. 2011
Fangjun Jiang
am 14 Okt. 2011
So is the function rand() the solution, or what do you really want to achieve?
sforza
am 14 Okt. 2011
Fangjun Jiang
am 14 Okt. 2011
Then, arrayfun() is probably what you are looking for. See update in the answer.
sforza
am 14 Okt. 2011
Andrei Bobrov
am 14 Okt. 2011
ds = arrayfun(@(i1)containsRandoms(p1),1:max1);
%if size of 'ds' m x n eg. 2 x 2
ds = reshape(arrayfun(@(i1)containsRandoms(p1),1:2*2),2,[]);
2 Kommentare
sforza
am 14 Okt. 2011
Fangjun Jiang
am 14 Okt. 2011
Search for "anonymous function" in documentation to understand @().
Diese Frage ist geschlossen.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!