Change values of a matrix if meet the condition
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
James Tursa
2018-11-2
编辑:James Tursa
2018-11-2
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
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!