USING MATLAB 1. The distance between two points (x 1 , y 1 ) and (x 2 , y 2 ) on
ID: 3562466 • Letter: U
Question
USING MATLAB
1. The distance between two points (x1, y1) and (x2, y2) on a Cartesian coordinate plane is given
by the equation
d =sqrt((x1 ? x2)2 + (y1 ? y2)2)
Write a function to calculate the distance between any two points (x1, y1) and (x2, y2) specified
by the user. Each point should be defined in the form of a vector. Use the program to calculate
the distance between the points (2,3) and (8,-5).
2. Write a function to evaluate
y(x) = ln ( 1/1 ? x )
for any value of x, where x is a number <1 (note that ln is the natural logarithm, the logarithm
to the base e). Use an if structure to verify that the value passed to the function is legal. If
the value of x is legal, calculate y(x). Now write a program with a while loop, so that the
program repeats the calculation of y(x) for each legal value of x entered into the program.
When an illegal value of x is entered, write a suitable error message and quit.
4. Write a program to evaluate the equation y(x) = x2 ? 3x + 2 for all values of x between 0.1
and 3, in steps of 0.1. Do this twice, once with a for loop and once with vectors. Plot the
resulting function using a 3-point thick dashed red line. Save the plot to a graphics file (e.g.
pdf or eps).
Explanation / Answer
Q1.
x1=input('enter the coordinates of first point (x coordinate , y coordinate format)');
x2=input('enter the coordinates of second point (x coordinate , y coordinate format)');
d=sqrt((x1(1)-x2(1))^2+(x1(2)-x2(2))^2);
x=['distance is ',num2str(d)];
disp(x)
Q2.
flag=0; %when this will be set, the program will quit
while flag==0
x=input('enter the number ');
if x >=1
flag=1;
disp('error');
else
y=log(1/(1-x));
answer=['answer is ',num2str(y)];
disp(answer)
end
end
Q3.
a=fopen('data.txt','r');
l=length(a);
sum1=0;
for i=1:l
sum1=sum1+a(i)^2;
end
avg=sum1/l;
rm=sqrt(avg);
x=['the rms value is ',num2str(rm)];
disp(x)
Q4.
%first with for loop
x=0.1:0.1:3;
y=zeros(1,length(x));
for i=1:length(x)
y(i)=x(i)^2-3*x(i)+2;
end
figure(1)
plot(x,y,'--r','lineWidth',3)
title('plot with for loop')
xlabel('x')
ylabel('y')
%second with vector
y=x.^2-3*x+2;
figure(2)
plot(x,y,'--r','lineWidth',3)
title('plot with vectors')
xlabel('x')
ylabel('y')
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.