Convert list of points into string and group it in tens

조회 수: 1 (최근 30일)
Askic V
Askic V 2022년 10월 21일
댓글: Askic V 2022년 10월 21일
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
sPoints =
'Points 1 to 10 9 7 10 10 4 10 8 9 8 4 6 1 2 9 7 1 4 2 9 9 Points 11 to 20 9 8 10 1 5 6 4 9 1 8 1 7 5 3 10 7 2 5 9 3 Points 21 to 30 2 4 7 4 6 10 7 7 6 6 8 10 2 6 1 2 8 5 5 1 Points 31 to 36 6 1 3 4 2 1 6 1 2 9 5 2 '

채택된 답변

Rik
Rik 2022년 10월 21일
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)
data = 4×1 cell array
{10×2 double} {10×2 double} {10×2 double} { 6×2 double}
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)
Points 1 to 10 5 2 5 4 1 4 4 4 6 10 10 7 9 9 9 5 10 9 5 9 Points 11 to 20 8 10 10 5 4 9 2 8 4 10 2 9 2 8 8 1 5 4 4 9 Points 21 to 30 2 7 3 9 4 3 5 4 8 2 10 10 9 10 10 6 1 10 7 4 Points 31 to 36 4 6 5 2 2 9 7 3 9 8 5 4
  댓글 수: 3
Rik
Rik 2022년 10월 21일
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.'
ans = 1.0000 - 1.0000i
ans = 1.0000 + 1.0000i
Askic V
Askic V 2022년 10월 21일
Cool, I didn't know this. Thanks again!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Whos에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by