How do I loop and save columns from a cell array as a double?
4 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Voss
2022-3-25
编辑:Voss
2022-3-25
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 个评论
Voss
2022-3-25
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!