Question

5.3) MATLAB Exercises 1. Extend the factorial function dened above, such that it checks for a...

5.3) MATLAB Exercises
1. Extend the factorial function dened above, such that it checks for a positive input argument.
2. Write a function that calculates a random walk trajectory based on the iteration xi+1 = xi + , where is a uniformly distributed random variable between -1 and 1. Plot the resulting trajectory.
3. Change the sorting algorithm given above such that it sorts the elements in descending order. Compare the speed of your function with the built-in MATLAB function sort.

4. Approximation of π. The area of a circle is given by A = πr2 where r is the radius. Assume a circle with r = 0.5 embedded in a unit square. A point in the unit square is dened by p = (x,y) where 0 ≤ x,y ≤ 1. If we draw ntot times two uniformly distributed random numbers (x,y) and count how often the corresponding points falls into the circle (ncirc), we get an approximation of the circle area by ncirc ntot and by that of the number π. Write a function which approximates π by the described method. How many draws do you need to get the rst three digits right?

part 2 to 4 missing

My answer part 1)

function y=calculate_factorial(n)

% check whether input argument is negative
if (n<0)
warning('Input argument must be non-negative');
disp('Ignoring the negative sign');
n=abs(n);
end
% check whether input argument is zero
if n==0
y=1;
else % otherwise calculate the factorial
y=n;
while n>1
n=n-1;
y=y*n; % calculate the factorial value
end
end
end

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Answer:-

function y=calculate_factorial(n)

% check whether input argument is negative
if (n<0)
warning('Input argument must be non-negative');
disp('Ignoring the negative sign');
n=abs(n);
end
% check whether input argument is zero
if n==0
y=1;
else % otherwise calculate the factorial
y=n;
while n>1
n=n-1;
y=y*n; % calculate the factorial value
end
end
end

  • SCREENSHOT OF CODE:

  • SAMPLE OUTPUT:

Add a comment
Know the answer?
Add Answer to:
5.3) MATLAB Exercises 1. Extend the factorial function dened above, such that it checks for a...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT