Can I use for loop to do the same process to four tables?
조회 수: 4 (최근 30일)
이전 댓글 표시
Hiya, Im trying to execute this for loop, but as well as changing the index, I also want to chnage the table that the original for loop is acting on.
I have four tables each with a different club name-
FMData_Test_BBSH_reordered
FMData_Test_NewCal_reordered
FMData_Test_3Wood_reordered
FMData_Test_Wooden_reordered
My original loop below works,
for i=1:13
%Use rotation matrix to rotate the offline (x) and Carry distance (y)
BBSH_x(i)=(FMData_Test_BBSH_reordered{i,3}.*cos(Theta_carry(1,1)))-(FMData_Test_BBSH_reordered{i,4}*sin(Theta_carry(1,1)));
BBSH_y(i)=(FMData_Test_BBSH_reordered{i,3}.*sin(Theta_carry(1,1)))+(FMData_Test_BBSH_reordered{i,4}*cos(Theta_carry(1,1)));
end
but rather than write this code out four times, each time changing the club name e.g.BBSH to the next club I was wondeirng if i could create another for loop to do this.
I have tried :
Club_names={'BBSH','New Cal','Ping 3 Wood','Wooden'};
for ii=Club_names
for i=1:13
%Use rotation matrix to rotate the offline (x) and Carry distance (y)
ii_x(i)=(FMData_Test_ii_reordered{i,3}.*cos(Theta_carry(1,1)))-(FMData_Test_ii_reordered{i,4}*sin(Theta_carry(1,1)));
ii_y(i)=(FMData_Test_ii_reordered{i,3}.*sin(Theta_carry(1,1)))+(FMData_Test_ii_reordered{i,4}*cos(Theta_carry(1,1)));
end
end
but this doesnt work as Matlab says the varibale FMData_Test_ii_reordered is not defined.
Any suggestions greatly appreciated.
댓글 수: 1
Stephen23
2019년 6월 28일
편집: Stephen23
2019년 6월 28일
"Any suggestions greatly appreciated. "
Do NOT put meta-data (e.g indices, club names, etc.) into variable names.
Why not?
Because then what happens is that you will try to access those names dynamically... and dynamically accessing variable names is one way that beginners force themselves into writing slow, complex, buggy code that is hard to debug. Read this to know why:
Meta-data is data, and data should be stored in a variable, not in a variable's name.
Your task would be trivial if you had stored this data in one array (e.g. a cell array, a table, etc.) and then just used simple, efficient indexing.
채택된 답변
Bob Thompson
2019년 6월 28일
To the best of my knowledge it is not possible to dynamically loop through variables. I would suggest combining the tables into one variable, perhaps a structure, and then looping through the index of that new variable.
structure = struct('table',{FMData_Test_BBSH_reordered, FMData_Test_NewCal_reordered, FMData_Test_3Wood_reordered, FMData_Test_Wooden_reordered});
for i = 1:length(structure)
% Do you stuff here. Call each table with structure(i).table
end
추가 답변 (0개)
참고 항목
카테고리
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!