MATLAB: Modifying the fprintf code.

dispfprintfMATLAB

Hello,
I have an assignment where the solution is shown and we are assinged to write the code that will duplicate the solution.
So far I have this:
n=9:-1:2;
theta=pi./n;
solution=cos(theta);
fprintf('cos(pi/n) = %7.5f\n',solution)
My problem is I am completely lost as to how to replace the n in my fprintf line with each of the decreasing values of n, so that it shows cos(pi/9), cos(pi/8), etc.
I've been searching MathWorks and using MatLab help to no avail. I have next to no background in coding or math language. (I am not looking for handouts, merely guidance.)

Best Answer

Replace the ‘n’ in ‘pi/n’ with the appropriate format descriptor. I chose ‘%d’ here, then concatenate the ‘n’ vector with the ‘solution’ vector in the fprintf call:
fprintf('cos(pi/%d) = %7.5f\n',[n; solution])
This only addresses part of your assignment (the rest of which you’ve already done), and is difficult to describe or provide hints for.
The full script is now:
n=9:-1:2;
theta=pi./n;
solution=cos(theta);
fprintf('cos(pi/%d) = %7.5f\n',[n; solution])