Manipulating Values in an Array with Logical Indexing
19 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Felix Tessarek
el 4 de Dic. de 2020
Comentada: Star Strider
el 5 de Dic. de 2020
I'm having problems with logical indexing of arrays
I do have an 10x10 array A. I want to change some of these values. Which values are changed is decided by a logical array 10x10 Array B.
Something like
A(B)=10
works perfectly. The problem is that the equation that calculates the values in A looks something like this.
A(B)=C^2+D^2
C and D are also 10x10 arrays. Ideally the Code would look like this:
A(B)=C(B)^2+D(B)^2
The values in C and D to be used in the equation have to be in the same row and column as in A. With two for-loops it would look like this:
for i=1
for u=1
if B(i,u)
A(i,u)=C(i,u)^2+D(i,u)^2
end
end
end
I'm not sure if the same can be achieved with logical indexing as C(B) just gives a vector as an output and of course then the dimensions do not agree. What i want to achieve is similar to:
A=C.^2+D.^2
but i only want to change some values of A, not all of them.
I tried reshaping the vectors as a matrix, but this only works if there arent any "holes" in the logical Matrix B.
Any help would be greatly appreciated
0 comentarios
Respuesta aceptada
Star Strider
el 4 de Dic. de 2020
The logical indexing approach should work as you described as wanting it to.
Try this example:
A = rand(5);
B = A < 0.5
C(B) = randi(99,1,nnz(B));
D(B) = randi(99,1,nnz(B));
A(B) = C(B).^2+D(B).^2
The correct values are replaced in the correct locations. The only significant change I made is to use element-wise exponentiation (.^ instead of ^).
6 comentarios
Star Strider
el 5 de Dic. de 2020
Felix Tessarek —
Thank you for posting the amplification and clarification!
Más respuestas (1)
Ameer Hamza
el 4 de Dic. de 2020
Editada: Ameer Hamza
el 4 de Dic. de 2020
You can use B as a mask
A=(C.^2+D.^2).*B
Only places in which B is not equal to zero will have non-zero output.
Ver también
Categorías
Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!