如何以优雅的方式编写此代码(MATLAB 中的元胞数组和结构体)
我想在 MATLAB 中绘制连接点。
我的连接点来自 "stats" 的连接对象,其中每个 "stat" 来自 BW Regionprops 结构。
我编写的代码可以工作,但它有很多“丑陋”,即使在尝试了各种方法之后我也无法修复。
function plot_line( line )
a = cell2mat(line);
b = {a.Centroid};
matx = {};
maty = {};
for i = 1:size(b,2)
matx{end+1} = b{i}(1);
maty{end+1} = b{i}(2);
end
plot ( cell2mat(matx), cell2mat(maty) );
end
你能帮我让这段代码变得更好吗?这并不重要,因为我的代码运行良好,并且行数很短(<100 点),因此性能不是问题。
只是如果知道这个小函数应该如何以正确的方式编写,而不需要 for 循环和 3 次 cell2mat 调用,那就太好了。
在我的示例中:
- line 是一个
<1xn cell>
, line{1}
具有属性'Centroid'
和line{ i}.Centroid(1)
是 x 坐标,line{i}.Centroid(2)
是 y 坐标。
实际上,我需要的只是为 i = 1:size( 绘制
,但我不知道如何。line{i}.Centroid(1)
, line{i}.Centroid(2)
line,2)
I would like to plot connected points in MATLAB.
My connected points come from connecting objects of "stats", where each "stat" comes from a BW regionprops struct.
The code I have written works, but it suffers from a lot of "ugliness", which I couldnt fix even after trying various ways.
function plot_line( line )
a = cell2mat(line);
b = {a.Centroid};
matx = {};
maty = {};
for i = 1:size(b,2)
matx{end+1} = b{i}(1);
maty{end+1} = b{i}(2);
end
plot ( cell2mat(matx), cell2mat(maty) );
end
Can you help me make this code nicer? It's not critical, as my code works fine and as the lines are short (<100 points) the performance is not an issue.
It is just that it would be really nice to know how this tiny function should be written in the proper way, without for loops and 3 calls of cell2mat.
In my example:
- line is a
<1xn cell>
, line{1}
has a property'Centroid'
andline{i}.Centroid(1)
are the x coordinates andline{i}.Centroid(2)
are the y coordinates.
Actually, all I need is plotting line{i}.Centroid(1)
, line{i}.Centroid(2)
for i = 1:size(line,2)
, but I don't know how.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 CAT:
编辑
如果你想保持它非常短(即甚至短于 @Amro的解决方案您可以使用CELLFUN 像这样以获得一句俏皮话:
Instead of creating a cell array
b
, you can create a numerical array directly, by catenating using CAT:EDIT
If you want to keep it really short (i.e. even shorter than @Amro's solution you can use CELLFUN like this in order get a one-liner:
示例:
您也可以这样做:
Example:
You could also do it as: