How to test a math function with different values of x?

17 views (last 30 days)
Hi all,
I am trying to take two math functions, (y and z) test them with 3 different values of x and print the results of each value in the two equations. I have made it so that I can test and print on of the values but I have not been able to modify my script to get it to test all 3 values and print the results. What I currently have follows:
%Clear command window and variables
clear
clc
%Naming Variables to make the equations cleaner
x = 1.2;
A = 3 * sin(x^3);
B = 4 * x + 3;
C = 2 * (x + 3);
D = exp(x) + 2;
E = 2 + 3 * x^3;
%Equations y and z, respectively
y = A./B;
z = C + (D./E);
%Print out the values of y and z
fprintf('For x=1.20 y is %0.06f, z is %0.06f', y, z)
This returns the following in the command window:
For x=1.20 y is 0.379873, z is 9.140551>>
Any help would be appreciated!

Accepted Answer

Jan
Jan on 5 Apr 2017
Edited: Jan on 5 Apr 2017
Move the equations into a function:
function [y, z] = Eqns(x)
A = 3 * sin(x^3);
B = 4 * x + 3;
C = 2 * (x + 3);
D = exp(x) + 2;
E = 2 + 3 * x^3;
y = A./B;
z = C + (D./E);
end
Now you can call this in a loop:
x = [1.2, 2.7. 3.1];
for k = 1:numel(x)
[y,z] = Eqns(x(k));
fprintf('For x=%.6f y is %.6f, z is %.6f\n', x(k), y, z);
end
'%0.06f' does the same as '%.6f' in sprintf.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by