Printing functions using fprintf

The prompt for the question has the user input vectors x y and scalar h, then compute some functions I have defined... The problem I'm having is, in the main script i have to print the row vectors x+y and z, one vector per line, using two decimal places for each element.
I have tried numerous fprintf statements such as
"fprintf ('x+y=%.2f+%.2f,x,y)
fprintf ('.%.2f +%.2f',x,y)
fprintf ('%.2f+%.2f=',x+y)"
etc...
however, while each element is rounded to two decimal places, and the addition is simple, it is not printing the way it is required. Any tips/help? Thank you!

Réponses (1)

Ameer Hamza
Ameer Hamza le 4 Nov 2020
If x and y are vectors then try this
x = 1:5;
y = 2:6;
fprintf('%.2f + %.2f\n', [x(:) y(:)].')
Result
1.00 + 2.00
2.00 + 3.00
3.00 + 4.00
4.00 + 5.00
5.00 + 6.00

4 commentaires

Joseph DeMaria
Joseph DeMaria le 4 Nov 2020
oh I see, that makes sense now, I had tried so many things, I was close at one point haha, thank you so much. Just wondering is there a way for it to display the answers as well in a column to the right i.e.
1.00 + 2.00 = 3.00
2.00 + 3.00 = 5.00
3.00 + 4.00 = 7.00
4.00 + 5.00 = 9.00
5.00 + 6.00 = 11.00
Yes, it is possible
x = 1:5;
y = 2:6;
z = x + y;
fprintf('%.2f + %.2f = %.2f\n', [x(:) y(:) z(:)].')
Joseph DeMaria
Joseph DeMaria le 4 Nov 2020
awesome, thank you so much. In terms of the questions guidlines it states "print the row vectors x+y and z, one vector per line, using two decimal places for each element." Would the format we have done above satisfy these conditions?
In other words is the format we have satisfactory? or would a code such as:
fprintf('The data table shows row vector x followed by row vector y, ending in the sum of x and y');
datatable=[x(:)';y(:)';xysum(:)']
which outputs :
The data table shows row vector x followed by row vector y, ending in the sum of x and y
datatable =
1 2 3
3 2 1
4 4 4
be better for these such conditions?
Ameer Hamza
Ameer Hamza le 4 Nov 2020
I think that the current results should be fine and fulfills the requirement. datatable you shared does not follow the rule for printing 2 decimal places.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Characters and Strings dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by