Effacer les filtres
Effacer les filtres

Overwriteing select values in multidimensional array

1 vue (au cours des 30 derniers jours)
Andrew Matteson
Andrew Matteson le 11 Oct 2023
Modifié(e) : dpb le 11 Oct 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

Réponse acceptée

Dyuman Joshi
Dyuman Joshi le 11 Oct 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);

Plus de réponses (1)

dpb
dpb le 11 Oct 2023
Modifié(e) : dpb le 11 Oct 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!!!

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Produits


Version

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by