Azzera filtri
Azzera filtri

count function, whwn i enter numbers and its wrong the count isnt going read the commnets i made

2 visualizzazioni (ultimi 30 giorni)
choice= input('Enter a vector sufficent for an odd-order polynomial: '); % inputs an even or odd vector [1]- odd [1 2]-even
a=length(choice);
Count = 1;
%b = mod(a,2);
while Count < 5 && mod(a,2)==0
choice= input('Enter a vector sufficent for an odd-order polynomial: ');
Count = Count+1; % this part isnt working for some reason
if Count > 5
warning('Odd number of coefficients entered. Last element removed');
choice(:,end)=[];
end
end
if mod(a,2)~=0
fprintf('Please enter a valid vector.\n');
end

Risposte (1)

Walter Roberson
Walter Roberson il 25 Feb 2020
Modificato: Walter Roberson il 25 Feb 2020
Suppose Count has reached 3 and mod(a, 2)==0. The loop will continue. choice will be input. Count will be incremented to 4. 4 is not greater than 5 so the last element of choice is not removed.
We return to the loop test. Count is 4 and that is less than 5. a has not changed so mod(a, 2) is still 0. So you will prompt for choice again, and then you will increment Count from 4 to 5. 5 is not greater than 5 so the last element of choice is not removed. Notice that the content of choice from the last iteration was ignored.
We return to the loop test. Count is 5 which is not < 5 so the loop terminates.
If you think about this, the test Count>5 can not be satisfied, so there is no point in having that code.
What went wrong? This:
You failed to update "a" after you changed the content of choice
  2 Commenti
Walter Roberson
Walter Roberson il 25 Feb 2020
My last paragraph already highlights what needs to be changed.
You initialize a when you read in choice the first time. After that you never change a. That is the mistake. You need to change a every time you change choice.

Accedi per commentare.

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by