Help with Function using Logical Indexing
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
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.
Risposte (1)
Guillaume
il 11 Mag 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:
- copy A into B
- create a logical array showing which elements of A are not divisible by k (your mod(A,k)~=0)
- 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.
0 Commenti
Vedere anche
Categorie
Scopri di più su Matrix Indexing in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!