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 个评论
采纳的回答
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|');
for k = 1:numel(x)
fprintf('%2d|%8.2f|%16.8f|%24.16e|\n',k,..);
end % ^^ hint: use indexing here!
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!