MATLAB Answers

How to use fprintf properly?

1 view (last 30 days)
Here is the question:
Write a script that does the following. Use fprintf and do not show scientific notaiton. NOTE: You will be able to reuse this code in Project 2. Publish your results from MATLAB in a Word document and upload here.
  • Generate an array y with 100 elements that is normally distributed with a mean of 2.5 and a standard deviation of 1 using the expression 2.5+1*randn(1). Notice you will get fractional results.
  • Determine the average y-value (use fprintf and avoid scientific notation). Use a for loop (do not simply use the command mean().)
  • Determine the number of y-values less than the number 2.0
PLEASE DO NOT GIVE ME THE COMPLETE ANSWER TO THIS WHOLE PROBLEM. I just want to know if I should split this question into three different sections using "%%" or if I should just lump the whole thing together. Also, I am trying to use fprintf and am having very little success. Do I put fprintf in three separate sections or just at the end of the whole problem? Thanks!

  0 Comments

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 9 Jan 2020
I just want to know if I should split this question into three different sections using "%%" or if I should just lump the whole thing together.
It does not matter to MATLAB. Some people find it easier to do debugging if they use %% seconds, but I find it to be more of a nuisance myself.
The one thing I would point out is that using %% is more likely to get you style points.
Do I put fprintf in three separate sections or just at the end of the whole problem?
It does not matter to MATLAB. However, it most of the time, people find it easier to read code that does outputing quite soon after computing the values to be output. There are, though, definitely cases where you are looking to create a formatted "report", and in such cases it often makes the most sense to compute the values and then call a report-creating function to create the report.

  0 Comments

Sign in to comment.

More Answers (1)

Tony Dimichele
Tony Dimichele on 9 Jan 2020
y = 2.5+1*randn(100,1)
histogram(y)
will produce a normally distributed histogram looking like.
fprintf('Hey') in the command line produces what for you?
fprintf('%.2f', y(1)) produces what for you?
If you use a for loop to find the mean, and name a variable after the value found, you can display the mean in the command window with an fprintf statement like above

  0 Comments

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!