Drexel dragonThe Math ForumDonate to the Math Forum



Search All of the Math Forum:

Views expressed in these public forums are not endorsed by Drexel University or The Math Forum.


Math Forum » Discussions » Software » comp.soft-sys.matlab

Topic: Compose a consecutive cell array from an output in a for loop
Replies: 1   Last Post: Jul 17, 2014 9:19 AM

Advanced Search

Back to Topic List Back to Topic List Jump to Tree View Jump to Tree View   Messages: [ Previous | Next ]
dpb

Posts: 8,232
Registered: 6/7/07
Re: Compose a consecutive cell array from an output in a for loop
Posted: Jul 17, 2014 9:19 AM
  Click to see the message monospaced in plain text Plain Text   Click to reply to this topic Reply

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()

--





Point your RSS reader here for a feed of the latest messages in this topic.

[Privacy Policy] [Terms of Use]

© Drexel University 1994-2014. All Rights Reserved.
The Math Forum is a research and educational enterprise of the Drexel University School of Education.