필터 지우기
필터 지우기

how to make a function that takes a matrix and integer and divide every divisible element of matrix by integer

조회 수: 2 (최근 30일)
Hi everyone I am going to attempt that query: Write a function called divvy that takes a matrix A of positive integers and a single positive integer k as its two inputs and returns a matrix B that has the same size as A. The elements of B are all divisible by k. If an element of A is divisible by k, then the corresponding element in B must have the same value. If an element of A is not divisible by k, then the corresponding element of B must be the product of the given element of A and k. You are not allowed to use any for-­‐loops or while-­‐loops. For example, the call X = divvy([1 2 ; 3 4], 2) would make X equal to [2 2 ; 6 4]. I am using that codes
function B =divvy(A,k)
if rem(A,k)==0
B=A;
else
B=A(:,:)*k;
end
end
but getting that error..
Feedback: Your function made an error for argument(s) [1 4;5 2;6 0], 3
Your solution is _not_ correct.
Any suggestion how can i correct my code? thanks in advance for assistance
  댓글 수: 1
Stephen23
Stephen23 2015년 5월 28일
편집: Stephen23 2015년 5월 28일
@Muhammad Usman Saleem: Your code concept is fundamentally flawed, because by using an if statement the allocation and multiplication operations are mutually exclusive, whereas they actually need to be able to operate on the same matrix. Using if does not help you! See my answer to know how this can be done.

댓글을 달려면 로그인하십시오.

채택된 답변

Stephen23
Stephen23 2015년 5월 28일
편집: Stephen23 2015년 5월 28일
There is no need to use slow find, when logical indexing is faster and neater:
function B = divvy(A, k)
B = A;
idx = rem(A,k)~=0;
B(idx) = k*A(idx);
end
And the test cases:
>> divvy([1,2;3,4], 2)
ans =
2 2
6 4
>> divvy([1,4;5,2;6,0], 3)
ans =
3 12
15 6
6 0
  댓글 수: 4
Stephen23
Stephen23 2015년 5월 28일
편집: Stephen23 2015년 5월 28일
function B = divvy(A, k)
% Allocate the output matrix:
B = A;
% Indices of A that are not multiples of k:
idx = rem(A,k)~=0;
% Multiply those element values by k:
B(idx) = k*A(idx);
end

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

charu sharma
charu sharma 2015년 8월 20일
There is no need of if else case, it can be done in one line. Refer this with explanation: http://farzicoders.blogspot.in/2015/08/write-function-called-divvy-that-takes.html

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by