필터 지우기
필터 지우기

FOR LOOP , beginner question.

조회 수: 4 (최근 30일)
Hamada Alkhlif
Hamada Alkhlif 2021년 4월 15일
편집: Jan 2021년 4월 15일
i want to Write a code or script including a FOR LOOP in order to computing the value of d for the following values of x and returning an output variable named ANSWER just as shown : x = 0.10, x = 0.15, and x = 0.20
  댓글 수: 3
Hamada Alkhlif
Hamada Alkhlif 2021년 4월 15일
sorry i forgot to entionb the eqation that we should use for d
  1. d=((34.63/x)-5.162)/2.54
  1. d = [];
  2. for x=[0.1000,0.1500,0.2000]
  3. d=[d ((34.63/x)-5.126)/2.54];
  4. disp ("ANSWER");
  5. end
  6. x=[0.1000 0.1500 0.2000];
  7. fprintf("\t%4g\t\t%4g\n",[x;d])
but when i put this cod into matlab it display like this
for x it shoulkd be 4 decimals .
DGM
DGM 2021년 4월 15일
편집: DGM 2021년 4월 15일
Try
fprintf("\t%8.4f\t%8.4f\n",[x;d])
using %g strips insignificant trailing zeros

댓글을 달려면 로그인하십시오.

채택된 답변

Daniel Pollard
Daniel Pollard 2021년 4월 15일
편집: Daniel Pollard 2021년 4월 15일
Your code is
d = [];
for x=[0.1000,0.1500,0.2000]
d=[d ((34.63/x)-5.126)/2.54];
disp ("ANSWER");
end
x=[0.1000 0.1500 0.2000];
fprintf("\t%4g\t\t%4g\n",[x;d])
If I understand right, you want
d = [];
x=[0.1000,0.1500,0.2000];
for xi = 1:numel(x)
d=[d ((34.63/x(xi))-5.126)/2.54];
disp ("ANSWER");
fprintf("\t%5.4f\t\t%.4f\n", [x(xi);d(xi)])
end
  댓글 수: 7
Hamada Alkhlif
Hamada Alkhlif 2021년 4월 15일
thank you @Daniel Pollard
Hamada Alkhlif
Hamada Alkhlif 2021년 4월 15일
thanks everybody

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Jan
Jan 2021년 4월 15일
편집: Jan 2021년 4월 15일
disp ("ANSWER");
for x = [0.10, 0.15, 0.20]
d = ((34.63 / x) - 5.126) / 2.54;
fprintf("%12g%12g\n", x, d)
end
Or:
x = [0.10, 0.15, 0.20]
d = ((34.63 ./ x) - 5.126) / 2.54; % .7 for elementwise division
fprintf('Answer:\n');
fprintf("%12g%12g\n", [x, d].')
  댓글 수: 1
Hamada Alkhlif
Hamada Alkhlif 2021년 4월 15일
1st code gives :
>> Untitled3
ANSWER
0.1 134.32
0.15 88.8743
0.2 66.1512
>> the answer here does not have 4 decimals for x' and not alighed vertically , same for d'
2nd code gives :
>> Untitled3
x =
0.1000 0.1500 0.2000
Answer:
0.1 0.15
0.2 134.32
88.8743 66.1512
>>

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by