Reputation: 1456
I have a 3x1 cell array that looks like this:
x={rand(256,901,160);rand(256,901,160);rand(256,901,160)};
[256x901x160 double]
[256x901x160 double]
[256x901x160 double]
I'd like to take the 3rd dimension and split it into 160 different 2d matrices, so 160 [256x901] matrices. I want to do this because i have written different functions that take in 2d matrices.
my desired output would be a 3x160 cell array containing matrices of 256x901.
I know i need to use reshape or mat2cell but I'm not too sure on the syntax.
EDIT
I found a slower way to do it but its not great..
for i = 1:length(x)
for k = 1:160
y{:,k}= x{i}(:,:,k);
end
end
any suggestions to improve speed?
Upvotes: 1
Views: 573
Reputation: 118
I tried some different approaches but I found that your own implementation is the fastest even compared to the the other solutions given. If you want more speed, you can consider a parfor loop. (parallel computing)
Upvotes: 1
Reputation: 10450
Here is an example with smaller arrays, it works on your example too:
x = {rand(3,4,5);rand(3,4,5);rand(3,4,5)};
y = cell(length(x),size(x{1},3));
for k = 1:length(x)
t = reshape(x{k},[size(x{1},1) size(x{1},2)*size(x{1},3)]);
y(k,:) = mat2cell(t,size(x{1},1),ones(size(x{1},3),1)*size(x{1},2));
end
on my computer it takes 0.36035 sec with your cell array.
Upvotes: 1
Reputation: 4644
How's this?
x ={rand(256,901,160), rand(256,901,160), rand(256,901,160)}';
x_1 = x{1};
x_2 = x{2};
x_3 = x{3};
two_d_arrays = cell(3, 160);
for k = 1:size(two_d_arrays, 2)
two_d_arrays{1, k} = x_1(:, :, k);
two_d_arrays{2, k} = x_2(:, :, k);
two_d_arrays{3, k} = x_3(:, :, k);
end
Upvotes: 0