fprintf the contents of a vector

조회 수: 126 (최근 30일)
Obadah M.
Obadah M. 2018년 11월 17일
댓글: madhan ravi 2018년 11월 18일
Hello,
As the title suggests, I want to display the contents of a vector in a fprintf command. I have read several posts about sprintf function and had no luck.
My current solution is this..... Is there any more efficient way to right it with less lines of codes?
fprintf('My first vector: ')
fprintf('%d ', vector1)
fprintf('\n')
fprintf('My second vector: ')
fprintf('%d ', vector2)
fprintf('\n')
fprintf('My third vector: ')
fprintf('%d ', vector3)
fprintf('\n')

답변 (3개)

madhan ravi
madhan ravi 2018년 11월 17일
편집: madhan ravi 2018년 11월 17일
EDITED
But this method is much faster than yours:
g=sprintf('%d ', vector1);
fprintf('Vector1 : %s\n', g)
g=sprintf('%d ', vector2);
fprintf('Vector2 : %s\n', g)
g=sprintf('%d ', vector3);
fprintf('Vector3 : %s\n', g)
Ran a loop to check the speed:
tic
for i = 1:100000
vector1 =1:10;
g=sprintf('%d ', vector1);
fprintf('Vector1 : %s\n', g)
end
toc
Elapsed time is 10.538184 seconds.
tic
for i = 1:100000
vector1 =1:10;
fprintf('Vector1 : ')
fprintf('%d ', vector1)
fprintf('\n')
end
toc
Elapsed time is 15.363047 seconds.
  댓글 수: 4
Image Analyst
Image Analyst 2018년 11월 17일
On my computer, my code below takes
Elapsed time is 0.000407 seconds.
so speed doesn't seem to be an issue worth worrying about.
madhan ravi
madhan ravi 2018년 11월 18일
True sir Image Analyst :)

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


Walter Roberson
Walter Roberson 2018년 11월 17일
Fewer lines of code but not necessarily any more efficient in execution:
fprintf( ['My first vector: ', repmat('%d ', 1, numel(vector1)), '\n'], vector1);

Image Analyst
Image Analyst 2018년 11월 17일
You could get rid of two of the fprintf's:
fprintf('My first vector: ')
fprintf('%d ', vector1)
fprintf('\nMy second vector: ')
fprintf('%d ', vector2)
fprintf('\nMy third vector: ')
fprintf('%d ', vector3)
fprintf('\n')

카테고리

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

태그

제품


릴리스

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by