Convert list of points into string and group it in tens

1 visualización (últimos 30 días)
Askic V
Askic V el 21 de Oct. de 2022
Comentada: Askic V el 21 de Oct. de 2022
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 '

Respuesta aceptada

Rik
Rik el 21 de Oct. de 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)
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 comentarios
Rik
Rik el 21 de Oct. de 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.'
ans = 1.0000 - 1.0000i
ans = 1.0000 + 1.0000i
Askic V
Askic V el 21 de Oct. de 2022
Cool, I didn't know this. Thanks again!

Iniciar sesión para comentar.

Más respuestas (0)

Community Treasure Hunt

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

Start Hunting!

Translated by