how can i print an array using fprintf function?

조회 수: 460 (최근 30일)
Salman Yahya
Salman Yahya 2019년 10월 22일
편집: dpb 2019년 10월 22일
i tried printing an array
array = [1 2 3];
with fprintf funtion,like this
fprintf('array = %1.0f', array);
but i am getting result in this form:
array = 1array = 2array3
can anyone help me resolving this problem?
i want to get result in this form
array = 1 2 3
or
array = [1 2 3]

채택된 답변

dpb
dpb 2019년 10월 22일
편집: dpb 2019년 10월 22일
You didn't put but one numeric formatting string in the format; hence, the whole thing repeats as often as needed to output the array. You needs must count the array and build the format string to match:
fmt=['array =' repmat(' %1.0f',1,numel(array))];
fprintf(fmt,array)
NB: The above will echo to screen w/ a newline which may or may not be desired behavior depending upon the application. If want to just display the above on the command line w/ next prompt on new line instead of at end of the string, have to add the \n explicitly:
fmt=['array =' repmat(' %1.0f ',1,numel(array)) '\n'];
One last little nuance: notice didn't put a blank after the '=' sign; that's in front of the numeric format string portion...one after the equal would end up doubling-up for the first element.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품


릴리스

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by