how to change variable name for iteration of vector computation?
3 次查看(过去 30 天)
显示 更早的评论
I am trying to create a loop that changes the variable name in each iteration, basically instead of coding " sec1_mean = mean(vel_sec1); sec2_mean = mean(vel_sec2); sec3_mean = mean(vel_sec3); sec4_mean = mean(vel_sec4); sec5_mean = mean(vel_sec5); sec6_mean = mean(vel_sec6); sec7_mean = mean(vel_sec7); " have a loop like
for i = 1:7
m_name2 = ['vel_sec' num2str(i)]
['sec' num2str(i) '_mean']= mean(m_name2)
end
but I have got error with this loop and the problem is that m_name2's class is char whereas we need it as double so that we can get the mean of say vel_sec1. I would appreciate any help on how I can solve this error.
Thanks
0 个评论
回答(2 个)
Star Strider
2014-10-20
编辑:Star Strider
2014-10-20
I suggest you create it as an array instead. It will be much easier to work with later:
for k1 = 1:7
sec_mean(k1) = mean(eval(sprintf('vel_sec%d',k1)));
end
The mean of all seven matrices is then: mean(sec_mean).
It would be best also to convert the ‘vel_sec#’ vectors to arrays as well, and delete the separate variables. You could use a numeric or cell array for those.
2 个评论
Star Strider
2014-10-20
The mean function defaults to taking the means of the columns. If you want to take the means of all the elements of each of the different matrices, this works:
% CREATE DATA
[vel_sec1, vel_sec2, vel_sec3, vel_sec4, vel_sec5, vel_sec6, vel_sec7] = deal(rand(3,4), rand(5,4), rand(7,4), rand(6,4), rand(3,4), rand(5,4),rand(4,4));
for k1 = 1:7
sec_mean(k1) = mean(eval(sprintf('vel_sec%d(:)',k1)));
end
grand_mean = mean(sec_mean);
I included the deal assignment I created to test my code, so you can look at it to be sure it matches your data.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!