How to let the user put matrix not single element and divisible each element in that matrix

1 view (last 30 days)
Make function called somthing(x) that loops through the vector x and for each number n in vector x it should display ‘n is divisible by 2’, ‘n is divisible by 3’, ‘n is divisible by 2 AND 3’ or ‘n is NOT divisible by 2 or 3’. Use a for loop, the function mod or rem to figure out if a number is divisible by 2 or 3, You can use any combination of if, else, and elseif. this is homework, i tried this code but
function[out]=divisible_m(x)
x=input('Enter any Vector')
if (rem(x,2)==0&&rem(x,3)==0)
disp('divisible on 2 and 3')
elseif (rem(x,2)==0&&rem(x,3)~=0)
disp('divisible on 2')
elseif (rem(x,2)~=0&&rem(x,3)==0)
disp('divisible on 3')
else
disp('not divisible ')
end
end
this code let user to enter just 1 element and my question is how to let the user put matrix not single element and divisible each element in that matrix

Accepted Answer

Bob Thompson
Bob Thompson on 26 Jul 2018
"Make function called somthing(x) that loops through the vector x and for each number ..." Your code does not currently have a loop within it, which is why it only works for single values. Because the prompt says, "for each number" a for loop is probably a good place to start.
Because you know that the code works for single values, then it means your conditional checks are most likely correct, which is the complex part of the problem. input() is able to receive any size matrix, whether 1x1 for single values, or MxN for more complex inputs. This means the input line most likely doesn't need to be changed.
The only thing left to do then is to create a loop so that the conditions are checked for each number.
  1 Comment
sami alzeq
sami alzeq on 30 Jul 2018
thank you it's finally working
function[out]=divisible_m(x)
x=input('Enter any Vector = ')
for n=1:1:length(x);
x(n)
if (rem(x(n),2)==0&&rem(x(n),3)==0)
disp('divisible on 2 and 3')
elseif (rem(x(n),2)==0&&rem(x(n),3)~=0)
disp('divisible on 2')
elseif (rem(x(n),2)~=0&&rem(x(n),3)==0)
disp('divisible on 3')
else
disp('not divisible')
end
end
end

Sign in to comment.

More Answers (0)

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!