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

1 次查看(过去 30 天)
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

采纳的回答

Bob Thompson
Bob Thompson 2018-7-26
"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 个评论
sami alzeq
sami alzeq 2018-7-30
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

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by