How to Overwrite Data

8 ビュー (過去 30 日間)
Nikolaos Zafirakis
Nikolaos Zafirakis 2019 年 7 月 8 日
編集済み: Stephen23 2019 年 7 月 8 日
The main objective is to overwrite the maximum values in matrix B with the values collected in matrix A
So I have:
A = (1:100,1) % A is the matrix with the results I need. So, A(1,1) = 4 , A(6,1) = 9
B = (1:100,1:2) % B always contains on each row a 0 and a value. Such as B(1,1:2) = 0 2 , B(6,1:2) = 53 0.
% Result would be for:
% C = (1:100,1:2) you would get C(1,1:2) = 0 4 , C(6,1:2) = 9 0
  2 件のコメント
madhan ravi
madhan ravi 2019 年 7 月 8 日
not clear , illustrate with a short example
Stephen23
Stephen23 2019 年 7 月 8 日
@Nikolaos Zafirakis: whatever you do, do NOT use loops for this! Using loops would be a waste of MATLAB's efficient code vectorization abilities:

サインインしてコメントする。

採用された回答

Stephen23
Stephen23 2019 年 7 月 8 日
編集済み: Stephen23 2019 年 7 月 8 日
One simple MATLAB way:
C = max(A,B).*(B~=0)
Or for MATLAB versions prior to R2016b:
C = bsxfun(@max,A,B).*(B~=0)

その他の回答 (2 件)

Abhishek Kumar
Abhishek Kumar 2019 年 7 月 8 日
for i= 1:100
if B(i, 1) == 0
B(i, 1)= A(i, 1);
elseif B(i, 2) == 0
B(i, 2) = A(i, 1);
end
end
The above bit of code should give you the desired output

Shameer Parmar
Shameer Parmar 2019 年 7 月 8 日
Here you go..
A = [1; 5; 7; 9; 4; 6; 8; 2; 3];
B = [4 0; 5 6; 8 0; 7 5; 0 8; 4 9; 5 6; 0 1; 2 8];
C = B;
for i = 1:length(B)
if B(i,1) == 0
C(i,2)= A(i,1);
elseif B(i,2) == 0
C(i,1)= A(i,1);
end
end

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by