Help with Function using Logical Indexing

1 view (last 30 days)
RG
RG on 11 May 2015
Answered: Guillaume on 11 May 2015
Hi, I'm trying to write a function, without using loops, which takes a matrix A and an integer k as inputs and returns a matrix B with same size as A. Elements of B are divisible by k. If an element of A is divisible by k, then the corresponding element in B has 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. For example, the call ([1 2 ; 3 4], 2) would return [2 2 ; 6 4]. I know that it is possible using logical indexing, but couldn't put it all together. Any help would be appreciated.
  1 Comment
Guillaume
Guillaume on 11 May 2015
This looks like homework, so if you want help with this you need to show what you've done so far

Sign in to comment.

Answers (1)

Guillaume
Guillaume on 11 May 2015
You've nearly got it. You don't want to contenate the results of the logical operations you've done. You want to replace the elements of a matrix according to the logical indexing.
I don't want to give you the full solution as it's homework, instead here are the steps I would follow:
  1. copy A into B
  2. create a logical array showing which elements of A are not divisible by k (your mod(A,k)~=0)
  3. Use the logical array to replace those elements of B that are not divisible by k by the same elements multiplied by k. You should have the logical array on both side of the =
That's all. You could have step 2 and 3 on the same line.

Tags

No tags entered yet.

Community Treasure Hunt

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

Start Hunting!