How can I use fprintf to print matrix by column?

99 ビュー (過去 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
  1 件のコメント
Niel Tran
Niel Tran 2021 年 9 月 16 日
Thank you very much!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeArgument Definitions についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by