Help with Function using Logical Indexing

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

Guillaume
Guillaume 2015-5-11
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.

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

尚未输入任何标签。

Community Treasure Hunt

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

Start Hunting!

Translated by