How to create a new variable in each iteration of the for loop?

6 views (last 30 days)
In the below code I want to trace the value of y.*win in each iteration so basically I am trying to create y_1 to y_5, the else part is the only one that has its total condition iterate and i'd rather keep it short like this but is there no solution to create the rest y_2 to y_4 without having to use elseif each time?
y = 1:10000 %for example
for winSize=[16,64,256,1024,4096]
if winSize == 16
win=zeros(size(y));
win(winSize:winSize*4) = 1;
y_1=y.*win;
elseif winSize == 4096
win=zeros(size(y));
win(winSize/2:winSize) = 1;
y_5=y.*win;
else
win=zeros(size(y));
win(winSize/2:winSize*4/2) = 1;
end
end

Accepted Answer

Alan Stevens
Alan Stevens on 17 Jan 2021
One way as follows:
y = 1024; %for example
winSize=[16,64,256,1024,4096];
for i = 1:numel(winSize)
if winSize(i) == 16
win=zeros(size(y));
win(winSize(i):winSize(i)*4) = 1;
Y(i)={y.*win};
elseif winSize(i) == 4096
win=zeros(size(y));
win(winSize(i)/2:winSize(i)) = 1;
Y(i)={y.*win};
else
win=zeros(size(y));
win(winSize(i)/2:winSize(i)*4/2) = 1;
Y(i)={y*win};
end
end

More Answers (0)

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!