필터 지우기
필터 지우기

How to replace array values that meet condition?

조회 수: 4 (최근 30일)
MCO
MCO 2019년 3월 6일
답변: Bob Thompson 2019년 3월 6일
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

답변 (1개)

Bob Thompson
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.

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by