Loop through every nth row in a data frame in a function
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Reuben Addison
le 22 Mar 2023
Réponse apportée : Sulaymon Eshkabilov
le 22 Mar 2023
I want to loop through specific rows to pick up data for some program I wrote and wondering if there is an efficient way of doing that. I have my coordinates in a matrix and each row represents a subject and the colums are the different orientation coordinates for a subject (see below)![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1333150/image.png)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1333150/image.png)
In my loop I want to go through each row (each row and pick e.g "nose" for for each subject)
%% Define coil position
S.poslist{1}.pos(1).matsimnibs = [-m0n0 m1n0 -m2n0 x; -m0n1 m1n1 -m2n1 y; -m0n2 m1n2 -m2n2 z; 0 0 0 1]
I want to achieve something like this below but selecting every 4th row
S.poslist{1}.pos(1).matsimnibs = [-TargetInfo.data(4) TargetInfo.data(7) -TargetInfo.data(10) TargetInfo.data(1); -TargetInfo.data(5) TargetInfo.data(8) -TargetInfo.data(11) TargetInfo.data(2); -TargetInfo.data(6) TargetInfo.data(9) -TargetInfo.data(12) TargetInfo.data(3); 0 0 0 1]
0 commentaires
Réponse acceptée
Sulaymon Eshkabilov
le 22 Mar 2023
The simpler and more efficient way would be using a logical indexing option or just use necessary indices, e.g.:
% DATA input/generation as a table array
TS = categorical({'Boy'; 'Boy';'Boy';'Boy'; 'Girl';'Girl';'Girl';'Girl';});
TN = categorical({'A'; 'B'; 'C'; 'D';'A'; 'B'; 'C'; 'D'});
DATA=table(TS);
DATA.TName=TN;
M1 = randn(numel(TN),1);
M2 = randn(numel(TN),1);
M3 = randn(numel(TN),1);
M4 = randn(numel(TN),1);
M5 = randn(numel(TN),1);
M6 = randn(numel(TN),1);
M7 = randn(numel(TN),1);
M8 = randn(numel(TN),1);
M9 = randn(numel(TN),1);
M10 = randn(numel(TN),1);
M11 = randn(numel(TN),1);
M12 = randn(numel(TN),1);
DATA.M1 = M1;
DATA.M2 = M2;
DATA.M3 = M3;
DATA.x = M4;
DATA.M5 = M5;
DATA.M6 = M6;
DATA.M7 = M7;
DATA.y = M8;
DATA.M9 = M9;
DATA.M10 = M10;
DATA.M11 = M11;
DATA.z = M12
% Logical indexing is used to take only 'A' or in your exercise: 'Nose'
% Note TName is a categorical data
CA=table2array(DATA(DATA.TName=='A', 3:end));
% Take out the necessary data and make some negative and leave some
% unchanged
Nose = [reshape(CA, 6, 4); 0 0 0 1].*[-1 1 -1 1]
% Alternative way:
CA2=table2array(DATA(1:4:end, 3:end));
Nose2 = [reshape(CA2, 6, 4); 0 0 0 1].*[-1 1 -1 1]
0 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!