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

조회 수: 4 (최근 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
Ive J
Ive J 2022년 2월 22일
Seems like homework to me.
Have you read fprintf help?
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