Help with Function using Logical Indexing

2 ビュー (過去 30 日間)
RG
RG 2015 年 5 月 11 日
回答済み: Guillaume 2015 年 5 月 11 日
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 日
This looks like homework, so if you want help with this you need to show what you've done so far

サインインしてコメントする。

回答 (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 Center および File ExchangeMatrix Indexing についてさらに検索

タグ

タグが未入力です。

Community Treasure Hunt

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

Start Hunting!

Translated by