gpuguy
gpuguy

Reputation: 4585

Dynamically creating and naming an array

Consider the following code snippet

for i = 1:100
    Yi= x(i:i + 3);   % i in Yi is not an index but subscript,
                    % x is some array having sufficient values
    i = i + 3
end 

Basically I want that each time the for loop runs the subscript changes from 1 to 2, 3, ..., 100. SO in effect after 100 iterations I will be having 100 arrays, starting with Y1 to Y100.

What could be the simplest way to implement this in MATLAB?

UPDATE

This is to be run 15 times

Y1 = 64;
fft_x = 2 * abs(Y1(5));

For simplicity I have taken constant inputs.

Now I am trying to use cell based on Marc's answer:

Y1 = cell(15,1); 
fft_x = cell(15,1); 

for i = 1:15
    Y1{i,1} = 64;
    fft_x{i,1} = 2 * abs(Y1(5));
end

I think I need to do some changes in abs(). Please suggest.

Upvotes: 2

Views: 116

Answers (3)

horchler
horchler

Reputation: 18484

Yes, you can dynamically name variables. However, it's almost never a good idea and there are much better/safer/faster alternatives, e.g. cell arrays as demonstrated by @Marc Claesen.

Look at the assignin function (and the related eval). You could do what asked for with:

for i = 1:100
    assignin('caller',['Y' int2str(i)],rand(1,i))
end

Another related function is genvarname. Don't use these unless you really need them.

Upvotes: 0

matheburg
matheburg

Reputation: 2180

It is possible to make variably-named variables in matlab. If you really want this do something like this:

for i = 1:4:100
    eval(['Y', num2str((i+3)/4), '=x(i:i+3);']);
end

How you organize your indexing depends on what you plan to do with x of course...

Upvotes: 0

Marc Claesen
Marc Claesen

Reputation: 17026

It is impossible to make variably-named variables in matlab. The common solution is to use a cell array for Y:

Y=cell(100,1);
for i =1:100
   Y{i,1}= x(i:i+3); 
   i=i+3;  
end 

Note that the line i=i+3 inside the for-loop has no effect. You can just remove it.

Y=cell(100,1);
for i =1:100
   Y{i,1}= x(i:i+3);   
end 

Upvotes: 1

Related Questions