Overwriteing select values in multidimensional array

3 次查看(过去 30 天)
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

采纳的回答

Dyuman Joshi
Dyuman Joshi 2023-10-11
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);

更多回答(1 个)

dpb
dpb 2023-10-11
编辑:dpb 2023-10-11
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!!!

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

产品


版本

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by