How to replace elements if it is true

Hi,
I have below cell array matrices:
A={'DF','3';'FR','4';'RR','2';'RT','4'};
B={'AB','1';'BC','3';'CD','5';'DF','7';'FR','9';'RT','8';'TA','1';'AR','3';'TY','4'};
if any of the row in B is member in A, the replace the corresponding second column element by seconf column element of A. I use the below code,
close all
clear all
clc
A={'DF','3';'FR','4';'RR','2';'RT','4'};
B={'AB','1';'BC','3';'CD','5';'DF','7';'FR','9';'RT','8';'TA','1';'AR','3';'TY','4'};
indx=ismember(B(:,1),A(:,1));
B(indx,2)=A(indx,2);
but it give the error:
??? Index exceeds matrix dimensions.
Error in ==> ScoreCompare at 7 B(indx,2)=A(indx,2);
My desired output should be:
AB 1
BC 3
CD 5
DF 3
FR 4
RT 4
TA 1
AR 3
TY 4
Many thanks in advance.

답변 (1개)

Jan
Jan 2017년 4월 18일
편집: Jan 2017년 4월 24일

0 개 추천

In B(indx,2)=A(indx,2) the index "indx" would concern both arrays. You need both outputs of ismember instead:
[LiB, LocA] = ismember(B(:,1), A(:,1));
B(LiB, 2) = A(LocA, 2); % [EDITED] Does not work for missing B
[EDITED]:
B(LiB, 2) = A(LocA(LiB), 2);

댓글 수: 3

Kanakaiah Jakkula
Kanakaiah Jakkula 2017년 4월 22일
It give an error:
??? Subscript indices must either be real positive integers or logicals.
Image Analyst
Image Analyst 2017년 4월 22일
Use isempty() to make sure LocA is not empty.
Jan
Jan 2017년 4월 24일
@Kanakaiah Jakkula: See [EDITED]

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

카테고리

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

태그

질문:

2017년 4월 18일

편집:

Jan
2017년 4월 24일

Community Treasure Hunt

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

Start Hunting!

Translated by