Trying to cycle through my variables with a for loop.
5 views (last 30 days)
Show older comments
matlabuser12
on 10 Jun 2015
Answered: Star Strider
on 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?
0 Comments
Accepted Answer
Star Strider
on 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
0 Comments
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!