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에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!