Clear Filters
Clear Filters

How to replace array values that meet condition?

4 views (last 30 days)
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

Answers (1)

Bob Thompson
Bob Thompson on 6 Mar 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.

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!