Borrar filtros
Borrar filtros

How to replace array values that meet condition?

4 visualizaciones (últimos 30 días)
MCO
MCO el 6 de Mzo. de 2019
Respondida: Bob Thompson el 6 de Mzo. de 2019
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

Respuestas (1)

Bob Thompson
Bob Thompson el 6 de Mzo. de 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.

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Productos


Versión

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by