How to replace array values that meet condition?
2 次查看(过去 30 天)
显示 更早的评论
Lets say there are two arrays:
A = [3 4 5];
B = [4 6 3];
Create another matrix B_1 with the elements in B and replace some:
%if the element in matrix B, is in matrix A, it does not matter the order: take value of element in matrix B.
%if the element in matrix B, is not in matrix,A, take a random number of matrix A, that is not in matrix B.
%expected output:
%B_1= [4 5 3];
%my try
B_1=B;
A_1=A;
size_b=size(B);
random_A=A_1(randperm(length(A_1)));
for ii = 1:size_b(1,2)
if B(ii)==A
B_1(ii)=B(ii)
else
B_1(ii)=random_A(ii)
end
end
output
B_1 =
5 3 4
0 个评论
回答(1 个)
Bob Thompson
2019-3-6
I'm assuming B_1 should be the same size as B? Does order matter?
If order doesn't matter:
A = [3 4 5];
B = [4 6 3];
B_1 = B(ismember(B,A));
if length(B_1)<length(B)
B_1 = [B_1, A(randperm(length(A),length(B)-length(B_1)))];
end
Whether order matters or not, you're not necessarily going to get your exact output you expect, because you're asking for a random value of A, not asking for a specific value.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!