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:
<1xn cell>
, line{1}
has a property 'Centroid'
and line{i}.Centroid(1)
are the x coordinates and line{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.
Example:
line = repmat({struct('Centroid',[1 2])},1,5); %# similar to the data you have
%# extract x/y coordinates
x = cellfun(@(s)s.Centroid(1),line)
y = cellfun(@(s)s.Centroid(2),line)
%# plot
plot(x,y)
You could also do it as:
xy = cell2mat(cellfun(@(s)s.Centroid, line, 'UniformOutput',false)');
plot(xy(:,1),xy(:,2))