How do I use fprintf and looping to create a table from a single randomized variable?

3 次查看(过去 30 天)
Hello, I'm fairly new to MATLAB and have run into a problem on an assignment. For part of my program, I am supposed to use this template:
disp('XX|XXXXX.XX|XXXXXXX.XXXXXXXX|XXX.XXXXXXXXXXXXXXXXe+NN|');
for i = 1:5
fprintf( WHAT is the command syntax here? Figure this out! );
end
(note that x is a randomly generated 1 by 5 array, so the exact numbers will vary)
To get exactly this output (with different numbers):
XX|XXXXX.XX|XXXXXXX.XXXXXXXX|XXX.XXXXXXXXXXXXXXXXe+NN|
1| -140.75| -140.74954935| -1.4074954934790074e+02|
2| 115.60| -115.59673565| 1.1559673565070500e+02|
3| -187.73| -187.73244361| -1.8773244361359698e+02|
4| -196.11| -196.11471589| -1.9611471588681820e+02|
5| -30.86| -30.86331752| -3.0863317521149384e+01|
As shown in the template, it appears that I am to get this output with a single fprintf command.
The closest I've come to this output is :
disp('XX|XXXXX.XX|XXXXXXX.XXXXXXXX|XXX.XXXXXXXXXXXXXXXXe+NN|');
fprintf(' %6.2f| %7.8f| %3.16e|\n',[x;x;x])
but this doesn't use the for loop and lacks the first column 1:5.
If x is already a 1 by 5 array, how can I also use a for loop and still only get 5 unique numbers as an output?
I'm completely stumped with this, so any help is greatly appreciated!
  2 个评论
John
John 2022-2-22
Yes, and I think I understand the basic syntax and how to write simpler fprintf commands, but am still running into issues getting fprintf to give the desired output while usung a loop given that x is an array rather than a single value

请先登录,再进行评论。

采纳的回答

Stephen23
Stephen23 2022-2-22
编辑:Stephen23 2022-2-22
Well, you made a reasonable start with this homework. I left small part for you to do:
x = [-1.4074954934790074e+02,+1.1559673565070500e+02,-1.8773244361359698e+02,-1.9611471588681820e+02,3.0863317521149384e+01];
disp('XX|XXXXX.XX|XXXXXXX.XXXXXXXX|XXX.XXXXXXXXXXXXXXXXe+NN|');
XX|XXXXX.XX|XXXXXXX.XXXXXXXX|XXX.XXXXXXXXXXXXXXXXe+NN|
for k = 1:numel(x)
fprintf('%2d|%8.2f|%16.8f|%24.16e|\n',k,..);
end % ^^ hint: use indexing here!
1| -140.75| -140.74954935| -1.4074954934790074e+02| 2| 115.60| 115.59673565| 1.1559673565070500e+02| 3| -187.73| -187.73244361| -1.8773244361359698e+02| 4| -196.11| -196.11471589| -1.9611471588681820e+02| 5| 30.86| 30.86331752| 3.0863317521149384e+01|

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by