How can I use fprintf to print matrix by column?

조회 수: 77 (최근 30일)
Niel Tran
Niel Tran 2021년 9월 16일
댓글: Stephen23 2021년 9월 17일
This is my code:
x = [1:0.6:4];
k = str2double (input ('Enter a value k: ','s'));
y = [x',(x.*k)',(x.^3)'];
disp ('The values of y are the following:');
y2 = [x.*k]';
y3 = [x.^3]';
fprintf ('%.4f %.4f %.0f\n',[x';y2;y3]);
I need to print the matrix y on the screen like this :
The values of y are the following:
1.0000 2.0000 1
1.6000 3.2000 4
2.2000 4.4000 11
2.8000 5.6000 22
3.4000 6.8000 39
4.0000 8.0000 64
But it keeps printed like this:
The values of y are the following:
1.0000 1.6000 2
2.8000 3.4000 4
2.0000 3.2000 4
5.6000 6.8000 8
1.0000 4.0960 11
21.9520 39.3040 64
Can someone help me with this? Thank you very much!
  댓글 수: 1
Stephen23
Stephen23 2021년 9월 17일
Removing all of the superfluous and confusing square brackets and complex conjugate tranposes makes your code simpler:
x = 1:0.6:4;
k = pi;
y = [x; x.*k; x.^3];
fprintf('%.4f %.4f %.0f\n',y);
1.0000 3.1416 1 1.6000 5.0265 4 2.2000 6.9115 11 2.8000 8.7965 22 3.4000 10.6814 39 4.0000 12.5664 64
If you want to write better code the solution is to get rid of pointless tranposes and the like, not keep on adding more on top.

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

채택된 답변

Image Analyst
Image Analyst 2021년 9월 16일
편집: Image Analyst 2021년 9월 16일
Use commas instead of semicolons:
x = [1:0.6:4]
k = str2double (input ('Enter a value k: ','s'));
y = [x',(x.*k)',(x.^3)']
disp ('The values of y are the following:');
y2 = [x.*k]'
y3 = [x.^3]'
fprintf ('%7.4f %7.4f %7.0f\n',[x',y2,y3]');
  댓글 수: 3
Image Analyst
Image Analyst 2021년 9월 16일
I forgot to transpose it in the fprintf(). Try this:
x = [1:0.6:4]
k = str2double (input ('Enter a value k: ','s'));
% y = [x',(x.*k)',(x.^3)']
disp ('The values of y are the following:');
y2 = [x.*k]'
y3 = [x.^3]'
fprintf ('%7.4f %7.4f %7.0f\n',[x',y2,y3]');
Enter 2 and you'll see:
1.0000 2.0000 1
1.6000 3.2000 4
2.2000 4.4000 11
2.8000 5.6000 22
3.4000 6.8000 39
4.0000 8.0000 64
>>
Niel Tran
Niel Tran 2021년 9월 16일
thank you very much!

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

추가 답변 (1개)

Rik
Rik 2021년 9월 16일
fprintf tranverses the input in a column-major order. If you want to change that, you can't, so you will have to flip the array itself:
x = [1:0.6:4];
k=2;%k = str2double (input ('Enter a value k: ','s'));
y = [x',(x.*k)',(x.^3)']
y = 6×3
1.0000 2.0000 1.0000 1.6000 3.2000 4.0960 2.2000 4.4000 10.6480 2.8000 5.6000 21.9520 3.4000 6.8000 39.3040 4.0000 8.0000 64.0000
%fprintf ('%7.4f %7.4f %7.0f\n',y.');
% ^^
fprintf ('%7.4f %7.4f %7.0f\n',y.');
1.0000 2.0000 1 1.6000 3.2000 4 2.2000 4.4000 11 2.8000 5.6000 22 3.4000 6.8000 39 4.0000 8.0000 64

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by