Effacer les filtres
Effacer les filtres

Create a 3D cell with vector elements of size 1x5 from five 3D matrices

2 vues (au cours des 30 derniers jours)
Ida
Ida le 3 Fév 2015
Commenté : Ida le 3 Fév 2015
Hello!
I have a structure of five 3D images (double,size 181x213x41). I would like to create a cell from this data, of same size as the 3D images (181x213x41) where each element will be a vector of size 1x5. I.e. the first vector element comes from 3D image 1, the second element from 3D image 2 and so on.
Example:
cellImage{i,j,k} = [1 2 4 1 0];
where
structure(1).image(i,j,k) = 1
structure(2).image(i,j,k) = 2
structure(3).image(i,j,k) = 4
structure(4).image(i,j,k) = 1
structure(5).image(i,j,k) = 0
I can do this by looping:
for i = 1:5
for j = 1:181
for k = 1:213
for l = 1:41
cellImage{j,k,l}(i) = structure(i).image(j,k,l);
end
end
end
end
This takes a very long time however. I want something similar to below (but that doesn't work).
for i = 1:5
cellImage{:,:,:}(i) = structure(i).image(:,:,:);
end
Does anyone know of a better way of doing this?
Thank you!

Réponse acceptée

Stephen23
Stephen23 le 3 Fév 2015
Modifié(e) : Stephen23 le 3 Fév 2015
This can be done without any loops which should be a lot faster. The basic concept is to join all of your data together into one numeric array, and then split it again to get the final vectors.
% Fake data: 1x2 struct, 2x3 numeric arrays, all unique values:
A(1).data = [9,8,7;6,5,NaN];
A(2).data = [0,1,2;3,4,Inf];
% Convert to a simple numeric array:
B = cat(4,A.data); % join along the fourth dimension :)
% Create dimension "indices":
C = arrayfun(@(n)ones(1,n),size(B),'UniformOutput',false);
C{4} = size(B,4);
% Use the "indices" to split the numeric array into a cell:
D = mat2cell(B,C{:});
% Optional: tidy-up by removing superfluous dimensions:
D = cellfun(@squeeze, D, 'UniformOutput',false);
Save this in a script and run it. Then in the command window you can check that it has grouped the data together corresponding to the same location in each of the original separate numeric arrays:
>> D{1,1}
ans =
9
0
>> D{1,3}
ans =
7
2
>> D{2,3}
ans =
NaN
Inf
Because I concatenated along the fourth dimension, it should also work for your 3D arrays.
Important: Do not use i or j as variable names, as these are both names for the inbuilt imaginary unit .
  1 commentaire
Ida
Ida le 3 Fév 2015
Hi Stephen and thank you for your response!
Your suggestion worked perfectly! =) Although the step
D = mat2cell(B,C{:});
still takes a bit of time, but is ok. Thank you again!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices 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!

Translated by