problem with fprintf command
조회 수: 3 (최근 30일)
이전 댓글 표시
i don't get the all values of the respective variable column wise.
Code:
close all
clear all
y = @(x) x.^3-x-11;
x = -10:1:10;
f = y(x);
fprintf('%8s %8s\n','x','f')
fprintf('%8.2f %8.2f\n',x',f')
what is wrong i can't find out. can anyone please help me.
Thanks in advance.
댓글 수: 1
VBBV
2023년 12월 5일
close all
clear all
y = @(x) x.^3-x-11;
x = -10:1:10;
f = y(x);
fprintf('%8s %8s\n','x','f')
fprintf('%8.2f %8.2f\n',[x;f])
채택된 답변
Walter Roberson
2023년 12월 5일
close all
clear all
y = @(x) x.^3-x-11;
x = -10:1:10;
f = y(x);
fprintf('%8s %8s\n','x','f')
disp(char(compose("%8.2f %8.2f",x',f')))
댓글 수: 2
Walter Roberson
2023년 12월 5일
When you use fprintf(), all of the first data parameter is converted (in linear order) before any of the second data parameter is converted. The form of fprintf() you used will not produce column outputs.
There is a way, though:
close all
clear all
y = @(x) x.^3-x-11;
x = -10:1:10;
f = y(x);
fprintf('%8s %8s\n','x','f')
fprintf('%8.2f %8.2f\n',[x; f])
This creates a 2D array with two rows, the first row of which is a value from x, and the second row of which is the corresponding value from f. And then "linear order" of the resulting array alternates elements of x and f, so columns can be output.
It takes a while to get accustomed to.
When you use compose(), then compose() knows to go across the data parameters using one value from each parameter, so compose() produces columns of output easily.
Walter Roberson
2023년 12월 5일
It might be easier to use compose() for output in this form
close all
clear all
y = @(x) x.^3-x-11;
x = -10:1:10;
f = y(x);
fprintf('%8s %8s\n','x','f')
fprintf("%s\n", compose("%8.2f %8.2f",x',f'));
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 String에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!