how to find out that the length is odd or even

5 vues (au cours des 30 derniers jours)
mohamed
mohamed le 19 Nov 2022
I'm working on this code:-
R = input('Enter the resistance values in Ohm, [R1....Rn]=');
n = length(R);
Nodd = (-1)^n;
while 1 % will check the values from 1 to n
if (Nodd ~= -1)
fprintf ('The number of resistors should be odd.\n');
R= input('Re-Enter the resistance values in Ohm, [R1....Rn]=');
else
break
end
end
disp ('==============================================================================');
and the problem is that it should check if the length of R is odd. if not, it should ask to re-enter an odd length of the answer but when the user inputs an even length and then re-enter an odd length the code keeps looping, so did i forget anything? or the code is wrong? and if there is any other way to type the even_odd code share it with me please. thanks

Réponse acceptée

VBBV
VBBV le 19 Nov 2022
Modifié(e) : VBBV le 19 Nov 2022
R = 0:0.1:9.1; % example with
n = length(R)
n = 92
while 1 % will check the values from 1 to n
Nodd = (-1)^n;
if (Nodd ~= -1)
fprintf ('The number of resistors should be odd.\n');
R= 93; % here the user enters odd sized vector 'Re-Enter the resistance values in Ohm, [R1....Rn]=';
n = length(R);
else
disp('The number of resistors are odd')
break
end
end
The number of resistors should be odd.
The number of resistors are odd
  3 commentaires
VBBV
VBBV le 19 Nov 2022
if you run the program as it is, it will not work since the new value of length is not entered yet. I disabled the input function in the if-block, because i cannot test it online, When you run it in standalone version of Matlab, you can enable input function and then enter resistance vector with odd number, it will work
mohamed
mohamed le 19 Nov 2022
it worked! thank you so much.

Connectez-vous pour commenter.

Plus de réponses (1)

Image Analyst
Image Analyst le 19 Nov 2022
Nodd = rem(n, 2)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by