How can I use fprintf to print matrix by column?

102 views (last 30 days)
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 Comment
Stephen23
Stephen23 on 17 Sep 2021
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.

Sign in to comment.

Accepted Answer

Image Analyst
Image Analyst on 16 Sep 2021
Edited: Image Analyst on 16 Sep 2021
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 Comments
Image Analyst
Image Analyst on 16 Sep 2021
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
>>

Sign in to comment.

More Answers (1)

Rik
Rik on 16 Sep 2021
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

Categories

Find more on Argument Definitions in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!