Question

I would like to know in matlab how to accomplish the following task:

If i have a for loop like in the following lines:

b=[1 2 3 4];
for i=1:1:10
x=i.*b
end

the code iterates i-times multiplying a scalar times the vector b; but if i put in the for loop x(i) in order to store the resulting vector of every iteration, i wouldn't get what i'm looking for. What i'm lookig for is to get:

x(1)=[1 2 3 4]
x(2)=[2 4 6 8]
... and so on
Was it helpful?

Solution

As in P0W's answer, you need a two-dimensional matrix to store "a vector of vectors". You can't use x(n), since addresses a single value in a one-dimensional matrix.

Another solution, maybe closer to what you want, is to use cell a cell array, which allow to create a matrix containing mixed-typed values (so you can put vectors too!). They are quite similar to regular array, but you need curly brackets:

b=[1 2 3 4];
x = cell(1,10);   % preallocating, not necessary but always a good idea

for i = 1:10
    x{i} = i*b  % notice the curly bracket with the index
end

note: you don't need the .* operator, since is a scalar-matrix multiplication.

You can get back your values with

x{1} = [1 2 3 4]    % again curly brackets
x{2} = [2 4 6 8]
...

OTHER TIPS

Can use:

x=[1:10]'*b

then

x(1,:)

x(2,:)

etc

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top