Clear Filters
Clear Filters

How can I use a for loop to name multiple variables?

2 views (last 30 days)
I have data for a range of walking and running speeds, and the number of speeds changes for each subject. Currently I have something like this, where the "_1" after "Head" and the number after "Walk" refers to the speed:
Head_1 = Walk1(:,1:eaVar); Head_2 = Walk2(:,1:eaVar); Head_3 = Walk3(:,1:eaVar);
Is there a way to put the speed number in a loop to shorten the code? The number of speeds varies from 7 to 22. I need each speed to be in its own matrix.
Many thanks.

Accepted Answer

Matt Tearle
Matt Tearle on 26 Mar 2011
Obligatory answer: don't. In your case, a 3-D array is probably the best option.
But if you have no option (because the Walk variables already have a number in them), use num2str to make a string to represent the command, including the variable name, then eval to evaluate that command. Something like
str = ['Head(:,:,k) = Walk',num2str(k),'(:,1:eaVar);'];
eval(str);

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices 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!