Sort vector A according to vector B

조회 수: 2 (최근 30일)
Aru E
Aru E 2022년 3월 27일
답변: Bruno Luong 2022년 3월 27일
I have two 14x1 vectors A and B. i am trying to sort A to match with B.
A = [0.9; 0.2; 0.4; 0.2; 0.3; 0.4; 0.7; 0.4; 0.1; 0.8; 0; 0; 0; 0];
B = [0; 0; 1; 1; 1; 1; 0; 0; 0; 0; 0; 0; 0; 0];
I am trying to make it so the 0's in A match with the 1's in B with a result of:
C = [0.9; 0.2; 0; 0; 0; 0; 0.4; 0.2; 0.3; 0.4; 0.7; 0.4; 0.1; 0.8]
This is my attempt:
TF1 = B(:,1)==1;
for j = 1:length(A)
n = j:length(B);
A(TF1,:) = 0
end
Any help would be appreciated. Thank you!
  댓글 수: 2
Image Analyst
Image Analyst 2022년 3월 27일
편집: Image Analyst 2022년 3월 27일
Why? What's the use case (context, reason)? Is it homework?
Did you try a simple for loop with two counters to keep track of indexes?
Aru E
Aru E 2022년 3월 27일
I am creating a program to automate a 2D truss solution. To solve for my reaction forces I need my displacement vector (A) to have the zeros lined up with my boundary conditions (B). I have not been able to successfully do this with a for loop or by sorting the vectors.

댓글을 달려면 로그인하십시오.

채택된 답변

Bruno Luong
Bruno Luong 2022년 3월 27일
A = [0.9; 0.2; 0.4; 0.2; 0.3; 0.4; 0.7; 0.4; 0.1; 0.8; 0; 0; 0; 0];
B = [0; 0; 1; 1; 1; 1; 0; 0; 0; 0; 0; 0; 0; 0];
Ais0=A==0;
Bis1=B==1;
C=zeros(size(A));
C(Bis1)=A(Ais0);
C(~Bis1)=A(~Ais0);
C
C = 14×1
0.9000 0.2000 0 0 0 0 0.4000 0.2000 0.3000 0.4000

추가 답변 (0개)

카테고리

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

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by