Convert list of points into string and group it in tens
3 views (last 30 days)
Show older comments
Hello,
I have a list of points which I want to convert to string and format it in a certain way.
I have manged to do this, but the code looks a bit complicated and wonder how this could be rewrite in a more efficient way.
points = randi(10,36,2);
points_len = size(points,1);
sPoints = '';
for kk = 1:points_len
if rem(kk+9, 10) == 0
if kk > points_len - rem(points_len,10)
endPoint = points_len ;
else
endPoint = kk+9;
end
sPoints = [sPoints, sprintf('Points %0.0f to %0.0f\n', kk, endPoint)];
end
sPoints = [sPoints, num2str(points(kk,:)), newline];
end
sPoints
0 Comments
Accepted Answer
Rik
on 21 Oct 2022
I would suggest putting each section in a cell, so you can easilly add the headers:
points = randi(10,36,2);
PointsPerSection = 10;
NumRows = ceil(size(points,1)/PointsPerSection);
rows = zeros(NumRows,1);
rows(1:(end-1)) = PointsPerSection;
rows(end) = size(points,1)-sum(rows); % Determine last element dynamically
data = mat2cell(points,rows,2)
for n=1:numel(data)
tmp = data{n};
HeaderPart = sprintf('Points %d to %d\n' ,...
(n-1)*PointsPerSection + 1 ,...
(n-1)*PointsPerSection + size(tmp,1) );
% The sprintf function allows providing arrays, but will process them
% by column, while humans will read the text by row. That is why we
% need to use .' to transpose the data.
DataPart = sprintf('%.0f %.0f\n',tmp.');
data{n} = [HeaderPart DataPart];
end
sPoints = horzcat(data{:});
disp(sPoints)
3 Comments
Rik
on 21 Oct 2022
You're welcome.
As to your question: habit. A single quote is not just the transpose, but the conjugate transpose. For real numbers there is no difference, but if you forget when working with complex number you will have a very difficult problem to debug. I try to learn myself good habits to avoid such bugs from ever occuring. For similar reasons I no longer use length when I actually mean numel (or I use size with an input argument).
a = 1+i;
a' , a.'
More Answers (0)
See Also
Categories
Find more on Whos in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!