2

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.

3 Answers 3

1

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 
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for your answer. Can you suggest based on my update above.
Indexing a cell array is always done using curly brackets {}. If you change fft_x{i,1}=2*abs(Y1(5)); to fft_x{i,1}=2*abs(Y1{5}); I think it will work.
0

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...

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.