Create a 3D cell with vector elements of size 1x5 from five 3D matrices
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
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!
0 comentarios
Respuesta aceptada
Stephen23
el 3 de Feb. de 2015
Editada: Stephen23
el 3 de Feb. de 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 .
Más respuestas (0)
Ver también
Categorías
Más información sobre Resizing and Reshaping Matrices en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!