For loops for functions that create structure arrays.
6 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(2 个)
Stephen23
2020-12-19
编辑:Stephen23
2020-12-19
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 个评论
Stephen23
2020-12-21
编辑:Stephen23
2020-12-21
"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:
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrices and Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!