I have two given matrices A and B in same size 5 x 5
A=[1 3 0 3 5; 2 3 4 1 0; 0 1 3 0 1; 2 4 5 4 4; 5 5 2 0 1]
B=[NaN NaN NaN NaN NaN; 2 3 4 1 NaN; 1 2 2 1 NaN; NaN 4 5 4 4; NaN 4 2 0 0]
How I could extract two sub-matrices of them - let's call them A1 and B1; by that B1 contains only numeric values of B, and A1 contains the corresponded values of A with same allocation index with numeric values of B. They should be like this
A1=[2 3 4 1; 0 1 3 0; 4 5 4 4; 5 2 0 1]
B1=[2 3 4 1; 1 2 2 1; 4 5 4 4; 4 2 0 0]
I tried for loops for a simple solution but it messed up. Thank you for your help~

 채택된 답변

KSSV
KSSV 2020년 4월 28일

1 개 추천

There should be more elegant method wituhut using loops.
clc; clear all ;
A=[1 3 0 3 5; 2 3 4 1 0; 0 1 3 0 1; 2 4 5 4 4; 5 5 2 0 1]
B=[NaN NaN NaN NaN NaN; 2 3 4 1 NaN; 1 2 2 1 NaN; NaN 4 5 4 4; NaN 4 2 0 0]
A1=[2 3 4 1; 0 1 3 0; 4 5 4 4; 5 2 0 1]
B1=[2 3 4 1; 1 2 2 1; 4 5 4 4; 4 2 0 0]
[m,n] = size(B) ;
A1 = cell([],1) ;
B1 = cell([],1) ;
count = 0 ;
for i = 1:m
idx = ~isnan(B(i,:)) ;
if any(idx)
count = count+1 ;
A1{count,1} = A(i,idx) ;
B1{count,1} = B(i,idx) ;
end
end
% The below works only when each cell has same number of elements
A1 = cell2mat(A1) ;
B1 = cell2mat(B1) ;

댓글 수: 3

Kien Pham
Kien Pham 2020년 4월 28일
Thank you for spending time with this question. The code you posted returns A1 and B1 as cell instead of matrices. It that possible to attain the matrices but not cell?
KSSV
KSSV 2020년 4월 28일
You can use cell2mat. I have given in the code right.
Kien Pham
Kien Pham 2020년 4월 28일
ahhh my fault :) I gazed on the loop part... Have a nice day :)

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

추가 답변 (1개)

dpb
dpb 2020년 4월 28일
편집: dpb 2020년 4월 28일

1 개 추천

A1=A.'; B1=B.'; % so can operate by row instead column...
isf=isfinite(B1);
>> B1=reshape(B1(isfinite(B1)),4,[]).'
B1 =
2 3 4 1
1 2 2 1
4 5 4 4
4 2 0 0
>> A1=reshape(A1(isf),4,[]).'
A1 =
2 3 4 1
0 1 3 0
4 5 4 4
5 2 0 1
>>

댓글 수: 1

Kien Pham
Kien Pham 2020년 4월 28일
편집: Kien Pham 2020년 4월 28일
Thank you for the response, it works well.

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

카테고리

도움말 센터File Exchange에서 NaNs에 대해 자세히 알아보기

질문:

2020년 4월 28일

편집:

2020년 4월 28일

Community Treasure Hunt

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

Start Hunting!

Translated by