Change values of a matrix if meet the condition
3 views (last 30 days)
Show older comments
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 Comments
Answers (1)
James Tursa
on 2 Nov 2018
Edited: James Tursa
on 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
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!