# how to compare previous and next values in MATLAB?

조회 수: 39(최근 30일)
zehra ülgen 2020년 11월 6일
댓글: Jon 2020년 11월 9일
Write a function called number_pattern that takes no input arguments and returns no output arguments. Instead it gets it input via the function input. It asks for a number repeatedly until the user puts in the same number twice in a row. The loop that it uses must be a while-loop. Here is an example run:
>> matching_number
Please input number (I'm looking for a pattern): 5
Sorry, that's not what I'm looking for.
Please input number (I'm looking for a pattern): 6
Sorry, that's not what I'm looking for.
Please input number (I'm looking for a pattern): 7
Sorry, that's not what I'm looking for.
Please input number (I'm looking for a pattern): 7
That's it. Well done!
The function should behave just as in the example, using exactly the same phrasing in its output (e.g., “That’s it. Well done!”)
I tried to write code but I did not understand how can I compare previous "b" and next "b". Here is my code..
##### 댓글 수: 4표시숨기기 이전 댓글 수: 3
zehra ülgen 2020년 11월 6일
'number repeatedly until the user puts in the same number twice in a row'
to do that statement I should compare the previous 'b value' and new 'b value'. But when I said b == b my code is not working. How can I compare last two b value?

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

### 채택된 답변

Mathieu NOE 2020년 11월 7일
hi
I believe this works :
function number_patter
b = [];
a = input ('Please input a number: ');
while 1
b = input ('Please input number (I''m looking for a pattern): ');
if a == b
fprintf('That''s it. Well done!\n');
return;
elseif b == prev_b
fprintf('That''s it. Well done!\n');
return;
else
fprintf('Sorry, that''s not what I''m looking for.\n');
end
prev_b = b;
end
##### 댓글 수: 2표시숨기기 이전 댓글 수: 1
Mathieu NOE 2020년 11월 8일
yes better this way ! :)

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

### 추가 답변(1개)

Jon 2020년 11월 6일
You need to create a new variable, call it for example prevB. After each loop set
prevB = B
when you do your comparison compare prevB and B
Note you will need to initialize prevB before entering the loop so it is defined the first time through. Just set it to something that the user would never enter for example prevB = inf
##### 댓글 수: 2표시숨기기 이전 댓글 수: 1
Jon 2020년 11월 9일
You need to assign prevB = b insinde of the loop

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

### Community Treasure Hunt

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

Start Hunting!

Translated by