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
댓글 수: 0
채택된 답변
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.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!