How do I loop and save columns from a cell array as a double?
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
lil brain
el 24 de Mzo. de 2022
Comentada: Voss
el 25 de Mzo. de 2022
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 comentarios
Respuesta aceptada
Voss
el 25 de Mzo. de 2022
Editada: Voss
el 25 de Mzo. de 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 comentarios
Voss
el 25 de Mzo. de 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.
Más respuestas (0)
Ver también
Categorías
Más información sobre Creating and Concatenating 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!