Search All of the Math Forum:
Views expressed in these public forums are not endorsed by
Drexel University or The Math Forum.


dpb
Posts:
8,872
Registered:
6/7/07


Re: Compose a consecutive cell array from an output in a for loop
Posted:
Jul 17, 2014 9:19 AM


On 07/17/2014 7:03 AM, Sofya wrote: > I have a basic question about for loops, which I just can't get my head > around. > > Generally, I have a function output of which is a single number, this > output I'm getting from a for loop. I want to then write each output > into a single cell. For example, if B is my function and A is the order > I need to use to call values from B: > > B=[15:30]; > A=[5 1 14 10 7]; > > for i=A > for j=1:length(A); > output{j}=B(i) > end > end > > which, of course, gives me that output > output = > [21] [21] [21] [21] [21]
The above will error on an array bounds with B=[15:30];
If B were, instead, a function expecting an integer input then it's possible, yes.
> instead of > > output= > > [19] [15] [28] [24] [21] > What approach should I use?
The loop would be
for i=1:length(A) output{j}=B(A(i)); end
The "Matlab way" would be to write B as a vectorized function and simply call
output={B(A)};
and alternative if don't vectorize B() would be to use arrayfun()



Date

Subject

Author

7/17/14


Sofya

7/17/14


dpb


