Overwriteing select values in multidimensional array

3 views (last 30 days)
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

Accepted Answer

Dyuman Joshi
Dyuman Joshi on 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);

More Answers (1)

dpb
dpb on 11 Oct 2023
Edited: dpb on 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!!!

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Products


Release

R2023b

Community Treasure Hunt

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

Start Hunting!