MATLAB: Using plot command in a loop

evalMATLABplotsprintf

Hey All,
I tried to change the input argument for plot command but it didn't work as I discovered that plot doesn't accept it as an input argument:
for i= 1:20
figure, plot((sprintf('Data%d',i))) , hold on; plot(f_mean*ones(length(sprintf('Data%d',i)),1),'r'); plot(sprintf('alpha_data%d',i),'g'); plot(sprintf('alpha_data_neg%d',i),'g'); hold off; axis ([0 350 0.28 0.32])
end
What can I change in my code to make it work??

Best Answer

if you want to change the variable name in the loop, use eval command
for i= 1:20,
figure(i),
eval(sprintf('plot(Data%d)',i));
hold on;
eval(sprintf('plot(f_mean*ones(1,length(Data%d)),''r'')',i));
eval(sprintf('plot(alpha_data%d,''g'')',i));
eval(sprintf('plot(alpha_data_neg%d,''g'')',i));
hold off;
axis ([0 350 0.28 0.32])
end
Related Question