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.

4

3 回答 3

1

在 matlab 中创建可变名称的变量是不可能的。常见的解决方案是对 Y 使用元胞数组:

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

请注意, -loopi=i+3内的行for无效。你可以删除它。

Y=cell(100,1);
for i =1:100
   Y{i,1}= x(i:i+3);   
end 
于 2013-05-18T10:30:09.203 回答
0

可以在 matlab 中创建变量命名的变量。如果您真的想要这样做,请执行以下操作:

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

你如何组织你的索引当然取决于你打算做什么x......

于 2013-05-18T23:12:48.587 回答
0

是的,您可以动态命名变量。但是,这几乎不是一个好主意,并且有更好/更安全/更快的替代方案,例如@Marc Claesen 演示的单元阵列。

查看assignin函数(和相关的eval)。您可以按照以下要求进行操作:

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

另一个相关的功能是genvarname。除非你真的需要它们,否则不要使用它们。

于 2013-05-18T23:26:28.293 回答