For loops for functions that create structure arrays.
6 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I've got two questions regarding the automation of the functions. I'm trying to create a for loop for each function.
For spm_vol: I would like to loop through a number of nifti files (P in the following syntax). V is a structure array.
V = spm_vol(P)
The following code works (i.e. produces a cell array containing one structure for each nifti file):
for i = 1:size(beta_list)
V = spm_vol(beta_list(:,i));
end
But it also gives the following error:
"Index in position 2 exceeds array bounds (must not exceed 1)."
Can you suggest any changes I need to make to avoid this error?
For clarity - beta_list is a 61x1 cell array containing file names.
I then want to use spm_read_vols for each structure, but this code doesn't work:
for j = 1:size(V)
[a, XYZ] = spm_read_vols(V(:,j));
end
The following error is produced:
Dot indexing is not supported for variables of this type.
Error in spm_check_orientations (line 24)
dims = cat(1,V.dim);
Error in spm_read_vols (line 25)
spm_check_orientations(V);
0 commentaires
Réponses (2)
Stephen23
le 19 Déc 2020
Modifié(e) : Stephen23
le 19 Déc 2020
Your indexing throws an error because beta_list has only one column but you are trying to access columns 2 to 61, which don't exist. As soon as your code tries to access the second (non-existent) column it will throw that error. A simpler and more robust approach is to use linear indexing rather than subscript indexing:
for k = 1:numel(beta_list)
V = spm_vol(beta_list{k});
... do whatever with V
end
2 commentaires
Stephen23
le 21 Déc 2020
Modifié(e) : Stephen23
le 21 Déc 2020
"Any thoughts?"
I guess that you didn't use any indexing into the output variable, in which case each iteration will simply overwrite the entire output variable (so after the last iteration only the output from the last iteration will remain). If the output of each iteration is a scalar structure with exactly the same fields and the output variable is not defined before the loop then you could just use indexing to implicitly create and allocate the output structure array:
for k = 1:numel(beta_list)
S(k) = spm_vol(beta_list{k});
end
Personally I prefer a slightly more robust approach of allocating to a preallocated cell array:
N = numel(beta_list);
C = cell(1,N); % preallocate cell array
for k = 1:N
C{k} = spm_vol(beta_list{k});
end
S = [C{:}]; % concatenate scalar structures into structure array
Read more:
Voir également
Catégories
En savoir plus sur Matrices and Arrays 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!