Creating array using other arrays and logical conditions.
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
Enkhzaya enkhtaivan
il 13 Ago 2020
Commentato: Enkhzaya enkhtaivan
il 13 Ago 2020
Hi, why does the below code return
Z = 0 0 0 0 1
X = [ -1 -2 3; -4 -5 -6];
Y = [ 3 3 3 ; 2 2 2];
M = ones(100);
Z (X > 0 & Y == 3) = M(X > 0 & Y ==3)
Only positive entry in X is at (1,3) position and Y = 3 at the first row of Y, so I expected something like 1 1 1 as the output.
I will appreciate if anyone can explain this to me, point me towards some tutorials about creating arrays in this way.
0 Commenti
Risposta accettata
Cris LaPierre
il 13 Ago 2020
Modificato: Cris LaPierre
il 13 Ago 2020
You have specified the index using a single array rather than a value for rows and a value for columns. In addition, your array is logical (true/false). In this case, the indexing is using linear indexing. Let's look at your data to explain.
Your index is created using
(X > 0 & Y ==3)
The result of which is
ans =
2×3 logical array
0 0 1
0 0 0
MATLAB uses column-major layout by default. The top left element is 1, the bottom left is 2, the top middle is 3, etc. Your index, therefore, is referencing element 5.
The code M(X > 0 & Y ==3) is therefore using linear indexing to extract the 5th element of M. Since M is 100x100, it is hard to tell, but it returns M(5), which here is the same as M(5,1), which is 1 (everyting is 1 in M).
Now for the final part. You also use linear indexing to assign this value to Z. In essense, you code says "take the 5th element of M and assign it to the 5th element of Z". Since Z has not yet been defined, MATLAB creates it as a row vector and adds the extracted value of M to the 5th spot. Since values 1-4 have not been defined, they are added as 0, again because, to add a value to the 5th spot, elements 1-4 have to exist first.
Hope that helps.
Più risposte (0)
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!