How can I use fprintf to print matrix by column?

85 visualizzazioni (ultimi 30 giorni)
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 Commento
Stephen23
Stephen23 il 17 Set 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.

Accedi per commentare.

Risposta accettata

Image Analyst
Image Analyst il 16 Set 2021
Modificato: Image Analyst il 16 Set 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 Commenti
Image Analyst
Image Analyst il 16 Set 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
>>

Accedi per commentare.

Più risposte (1)

Rik
Rik il 16 Set 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

Categorie

Scopri di più su Argument Definitions in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by