How can I use fprintf to print matrix by column?

82 次查看(过去 30 天)
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
>>

请先登录,再进行评论。

更多回答(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