Change values of a matrix if meet the condition
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Hi guys a have a 2*2 matrix. and I want to substite the values of the 2 columns based in 2 different conditions. EX a= '1' '0' '0' '1'. For the first column if X=1 y=0.6 and if X=0 y=0.4. Similarly in column 2 if x=1 y=0.7 and if x=0 y=0.3. Therefore, new matrix b= '0.6' ' 0.4' '0.3' '0.7'.
2 Kommentare
Antworten (1)
James Tursa
am 2 Nov. 2018
Bearbeitet: James Tursa
am 2 Nov. 2018
E.g., I think this is what you are asking for:
a = your matrix of 1's and 0's
p = your matrix of values (1st row corresponding to 0 values, 2nd row corresponding to 1 values)
c = 1:size(a,1):numel(a); % Set up for linear indexing
b = a; % An arbitrary matrix the same size as a
b(:) = p(bsxfun(@plus,a,c)); % Replace elements with appropriate p values (linear indexing)
On later versions of MATLAB you don't need bsxfun:
b(:) = p(a+c); % Replace elements with appropriate p values (linear indexing)
A sample run:
>> a = eye(2)
a =
1 0
0 1
>> p = [0.4 0.3; 0.6 0.7]
p =
0.4000 0.3000
0.6000 0.7000
>> c = 1:size(a,1):numel(a)
c =
1 3
>> b = a
b =
1 0
0 1
>> b(:) = p(bsxfun(@plus,a,c))
b =
0.6000 0.3000
0.4000 0.7000
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!