Trying to cycle through my variables with a for loop.

5 Ansichten (letzte 30 Tage)
matlabuser12
matlabuser12 am 10 Jun. 2015
Beantwortet: Star Strider am 10 Jun. 2015
for i=1:20
Data = sprintf('Data%i',i);
DataNew(:,i) = mean(Data);
end
I have 20 Data arrays labeled Data1-Data20 and want to cycle through them in a for loop and do some calcs like mean, or run them all through a formula. But I keep getting errors that the Data is a char, how do I do this correctly?

Akzeptierte Antwort

Star Strider
Star Strider am 10 Jun. 2015
I would do it in two steps, first to create a cell array from the individual arrays (so you don’t have to go through that step ever again), and second, calculate the means:
Data1 = randi(10, 5, 1); % Create Data
Data2 = randi(10, 7, 1);
N = 2;
for k1 = 1:N
Data{k1} = eval(sprintf('Data%d',k1)); % Create Cell Array From Individual Arrays
end
for k1 = 1:size(Data,2)
DataNew(k1) = mean(Data{k1});
end

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by