Given: Write a script that creates a random integer N, which is in the range [-100,100]. If that number is in the range [-20,20], reassign N to be the current value of N multiplied by 2. If the number is greater than 20, reassign N to be the square root of the current value. Otherwise, reassign N to be the current value divided by 4.
Find: Use an if-statement to complete this.
Issue: I'm getting errors stating I don't know how to use '='. To me, my solution makes sense. But I have trouble with syntax in MATLAB.
My Solution:
N=randi([-100,100]);
if N=[-20,20]
N=N*2
else if N>20
N=sqrt(N)
else
N=N/4
end

 채택된 답변

Voss
Voss 2024년 3월 22일

1 개 추천

Use
if N >= -20 && N <= 20
And remove the space in "else if".

댓글 수: 5

Spaceman
Spaceman 2024년 3월 22일
Eureka! Of course. Now I get it. I want to accept both yours and Mr. Lords answer, but unfortunately I can only pick one.
Voss
Voss 2024년 3월 22일
Glad it makes sense!
Spaceman
Spaceman 2024년 4월 8일
Thank you so much for your help!
Voss
Voss 2024년 4월 8일
You're welcome!
Spaceman
Spaceman 2024년 4월 8일
You're a real one!

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

추가 답변 (1개)

Steven Lord
Steven Lord 2024년 3월 22일

2 개 추천

Let's look at the exact text of the error you received.
N=randi([-100,100]);
if N=[-20,20]
Incorrect use of '=' operator. Assign a value to a variable using '=' and compare values for equality using '=='.
N=N*2
else if N>20
N=sqrt(N)
else
N=N/4
end
Using "N = [-20 20]" attempts to assign a vector with two elements to N. Assignment is not allowed in the condition part of an if statement.
Using "N == [-20 20]" (assuming N is compatibly sized) compares elements of N with elements of the vector [-20 20]. Comparison is allowed in the condition part of an if statement.
But you don't want to check if the elements in N are equal to -20 and 20. You want to check if they're in that interval. For that use the four inequality relational operators like < and >=. The and, & and or, | operators will also be of use.

댓글 수: 1

Spaceman
Spaceman 2024년 3월 22일
Genius. This makes complete sense I forget I am generally only using logical operators with if and elseif statements. Also as Voss pointed out, I had a space in my elseif. Thank you for clearing that up.

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

카테고리

도움말 센터File Exchange에서 2-D and 3-D Plots에 대해 자세히 알아보기

제품

릴리스

R2023b

태그

질문:

2024년 3월 22일

댓글:

2024년 4월 8일

Community Treasure Hunt

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

Start Hunting!

Translated by