필터 지우기
필터 지우기

Help with Function using Logical Indexing

조회 수: 10 (최근 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 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