Plot all polyshapes in cell array

9 次查看(过去 30 天)
Hello,
I am learing Matlab and I would like to plot all polyshapes stored in a cell array (D) but avoiding for...end loop.
Each cell contains a 2d vector with each vertex coordinates.
So far I only know to plot it like this
for i=size(D,1)
plot(D{i}(:,2), D{i}(:,1));
end
Is there any more concise way to achieve it with a single instruction not using a for...end loop?
Thanks

采纳的回答

Voss
Voss 2022-5-7
You could use cellfun:
cellfun(@(x)plot(x(:,1),x(:,2)),D);
That's more concise, I guess, but it also may be less clear than the loop you already have. And it's not likely to be much different performance-wise.
[In general, cellfun(f,C) runs the function f on each cell of cell array C. In this case, the function is the anonymous function
@(x)plot(x(:,1),x(:,2))
and the cell array is D.]
  2 个评论
Luis Rosety
Luis Rosety 2022-5-8
编辑:Luis Rosety 2022-5-8
Thanks!
This is what I was looking for: A single command.

请先登录,再进行评论。

更多回答(1 个)

Steven Lord
Steven Lord 2022-5-8
If you've already created them in a cell array you can simply turn that cell array into an array of polyshape objects and plot that array. Or you could start with a polyshape array initially, filling it in as you go.
C = cell(1, 10);
A1 = repmat(polyshape, 1, 10);
for k = 1:10
N = nsidedpoly(1000, 'Center', [2*k 0], 'Radius', 0.75);
C{k} = N; % Create a cell
A1(k) = N; % Fill in an array
end
A = [C{:}]
A =
1×10 polyshape array with properties: Vertices NumRegions NumHoles
plot(A)
axis equal
grid on
A1
A1 =
1×10 polyshape array with properties: Vertices NumRegions NumHoles
figure
plot(A1)
axis equal
grid on
  2 个评论
Luis Rosety
Luis Rosety 2022-5-8
This doesn't work in my case.
It throws an error:
Error using horzcat
Dimensions of arrays being concatenated are not consistent.
Steven Lord
Steven Lord 2022-5-8
Ah, I went off the subject of the message. You don't actually have polyshape objects in a cell array, you have coordinate data in the cell array. In that case, a skeleton for the approach I'd use:
% C is the cell array of coordinate data
P = repmat(polyshape, size(C)); % One polyshape per cell in C
for k = 1:numel(C)
data = C{k};
P(k) = polyshape(data(:, 2), data(:, 1));
end
plot(P)
I'm assuming the data in the cell array matches the requirements the polyshape function has for its inputs.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Elementary Polygons 的更多信息

产品


版本

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by