How do I loop and save columns from a cell array as a double?
3 views (last 30 days)
Show older comments
Hi,
I have a cell of doubles array which contains 19 cells. I am looking to build a for loop which saves the first three columns of each cell as a seperate three-column vector. In the end I would like to end up with 19 three-column vectors (19 variables).
How would that look?
Thank you!
0 Comments
Accepted Answer
Voss
on 25 Mar 2022
Edited: Voss
on 25 Mar 2022
You don't want 19 separate variables. Just make another cell array.
S = load('cell_of_doubles.mat');
S.cell_of_double_balls
% you don't need a loop:
C = cellfun(@(x)x(:,1:3),S.cell_of_double_balls,'UniformOutput',false)
% but here's one anyway:
C = cell(size(S.cell_of_double_balls));
for ii = 1:numel(C)
C{ii} = S.cell_of_double_balls{ii}(:,1:3);
end
C
2 Comments
Voss
on 25 Mar 2022
dist = sqrt(sum(C{1,1}(:,1:3),1,1).^2);
% ^^ third input to sum()
The third input argument to the sum function must be a character vector saying 'double', 'native', 'default', (to specify the output class) 'omitnan', or 'includenan' (to specify how the summation should treat NaNs). This is what the error message means.
If C{1,1}(:,1:3) is a matrix of (x,y,z) coordinates, then maybe you intend to calculate the distance between adjacent points in the matrix i.e., points in adjacent rows of C{1,1}(:,1:3), which involves taking the difference of adjacent (x,y,z) coordinates, to get (dx,dy,dz), then squaring those values, adding dx^2+dy^2+dz^2, and finally taking the square root (the distance formula):
dist = sqrt(sum(diff(C{1,1}(:,1:3),1,1).^2,2));
(Read about the second and third arguments to diff and the second argument to sum to know what they are for.)
If that's what you want it to do, then that will work whether the first argument to the sum function is its own variable or three columns from a matrix contained in a cell array, which it is here.
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!