Overwriteing select values in multidimensional array

3 visualizaciones (últimos 30 días)
Andrew Matteson
Andrew Matteson el 11 de Oct. de 2023
Editada: dpb el 11 de Oct. de 2023
Hello All,
I'm having issues with changing select values of an array. I'm able to create a logical matrix (loc#) that meets my conditions and then get an array with the values I want, (val). However, I can't think/google a way to contine to change values in val, (ex. val==0), with out overwriting all the values in val.
tmp1 = (rand(5,5,5)-.5)*10;
tmp2 = (rand(5,5,5)-.5)*10;
loc1 = tmp1 > 0;
val = tmp1.*loc1;
loc2 = tmp2 > 0;
val(loc2) = tmp2.*loc2;
% val(val) = tmp2.*loc2;
% val(val==0) = tmp2.*loc2;
% val(:) = tmp2.*loc2;
Any help with this would be appreciated. Thanks in advance

Respuesta aceptada

Dyuman Joshi
Dyuman Joshi el 11 de Oct. de 2023
tmp1 = (rand(5,5,5)-.5)*10;
tmp2 = (rand(5,5,5)-.5)*10;
loc1 = tmp1 > 0;
%This is a shortcut way of logical indexing
val = tmp1.*loc1;
loc2 = tmp2 > 0;
%Use logical indexing
val(loc2) = tmp2(loc2);
You can do logical indexing for both conditions -
%Preallocate the output array
val = zeros(size(tmp1)); %you can preallocate NaN as well
loc1 = tmp1 > 0;
val(loc1) = tmp1(loc1);
loc2 = tmp2 > 0;
val(loc2) = tmp2(loc2);

Más respuestas (1)

dpb
dpb el 11 de Oct. de 2023
Editada: dpb el 11 de Oct. de 2023
You're just making it harder than it is...
tmp1 = (rand(5,5,5)-.5)*10;
loc1 = tmp1 > 0;
tmp1(loc1)=123456; % Use the force (aka addressing vector), Luke!!!

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by