how to find out that the length is odd or even

5 views (last 30 days)
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

Accepted Answer

VBBV
VBBV on 19 Nov 2022
Edited: VBBV on 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 Comments
VBBV
VBBV on 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

Sign in to comment.

More Answers (1)

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

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!