How to replace array values that meet condition?
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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 Kommentare
Antworten (1)
Bob Thompson
am 6 Mär. 2019
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 Kommentare
Siehe auch
Kategorien
Mehr zu Creating and Concatenating Matrices 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!