user2260180
user2260180

Reputation: 275

Extractig data from cell array

In this MWE, I generate dis (x, y, z displacements for nodes and increments), I then need to extract separately the displacements

clear
k=0;
% ignore following, this is just to buils dis
for node=1:20
   for incr=1:100
       k=k+1;
       dis{node,incr}(1)=k; % X coordinate
       dis{node,incr}(2)=2*k; % Y coordinate
       dis{node,incr}(3)=3*k; % Z coordinate
   end
end

I would like to build U, V, W arrays from dis. However, the following statement fails:

U(:,:)=dis{:,:}(1);

Any concise way to make that substitution?

Upvotes: 2

Views: 105

Answers (2)

Edric
Edric

Reputation: 25160

This is a bit fiddly. Your dis array is a cell matrix where each entry is a 1x3 double array. I think the first step has to be to get rid of the cell-ness and create a regular double array. You can do that as follows:

arr = [dis{:}];

This takes the cells of dis in column-major order, and then horizontally concatenates them into one big long vector. You can reshape this into a 3D array by carefully observing the order of the entries:

reshaped = reshape(dis, 3, 20, 100);

This has the entries in a 3D array, but the dimensions are permuted. So, you can use permute to fix it up:

fixed = permute(reshaped, [2, 3, 1]);

You can then get out U by doing

U = fixed(:,:,1)

Upvotes: 1

Luis Mendo
Luis Mendo

Reputation: 112749

You can use

U = cellfun(@(d) d(1), dis); % change index 1 to 2, 3 for V, W

Alternatively,

dis_3D = cell2mat(permute(dis, [1 3 2]));
U = permute(dis_3D(:,1,:), [1 3 2]); % change index 1 to 2, 3 for V, W

However, consider defining dis directly as a 3D array (of size 20×100×3 in your example), and then everything will be easier. There seems to be no need for a cell array here.

Upvotes: 1

Related Questions