0

I want to store an array which changes its size in each iteration of a for loop. For example,

for y=1:100
    for x=1:50
.
.
        ms(:,x,y) = ans;
.
.
    end 
end

The 'ans' is a row vector which changes its size in each iteration of y.

How can i store these variable length 'ans' into ms?

When i try to initialize 'ms' as cell, it shows an error saying "Conversion to cell from double is not possible."

What are the ways i can solve this?

Thanks Kind regards

Kave
  • 1
  • 1

2 Answers2

1

One way to do this:

ms = {};
for y=1:100
    for x=1:50
       ms = [ms 1:x];
       % or
       % ms = [ms new_cell_element];
    end 
end

You can also index the cell array with ms{x,y} = 1:3; new_cell_element does not need to be a cell, it can be anything you want.

ms = [ms, 'A string', (1:5).'] %// Works! 

Note that I do not recommend this, and I'm pretty sure there are other ways to do this, depending on what you want to do inside those nested loops. You should check out cellfun, and read up on cells in general.

Also, never ever use ans as a variable name in MATLAB. That will only cause you trouble. Any other name is better (except clear and builtin).

Community
  • 1
  • 1
Stewie Griffin
  • 14,889
  • 11
  • 39
  • 70
1

The only way I can think of is to indeed use a cell array. Initialize a 2D cell array like so:

ms = cell(50,100);

After, you index into the cell by using curly braces ({}). Therefore, your loop will look like:

for y=1:100
    for x=1:50
.
.
        ms{x,y} = ans;
.
.
    end 
end

After you're done, you can index into the cell array by choosing the row and column location you want:

vec = ms{row,col};

BTW, I don't recommend you use ans as a variable. ans is the default variable that is used when you execute a statement in MATLAB which has an output and you don't specify a variable of where this output from the function will go. You may have code that will overwrite the ans variable, so you should perhaps use another name.

rayryeng
  • 102,964
  • 22
  • 184
  • 193