Two cells merged together with different conditions

1 view (last 30 days)
I want cell a and b merged together.
1) When one of the two string as a value (as 5,6 or 7) I want c to have that value.
2) When the two cells has both the letter A and B, I want array c to have the letter A.
3) When the cells string has the letter A , I want array c to have the letter A.
4) When the cells string has the letter B , I want array c to have the letter B.
%Given cells
a={'A'; 'B' ; 5 ; 6; 'A' ; 'A'; 'B'};
b={ 7; 'B' ;'A' ;'B'; 'A' ; 'B' ; 'A'};
%Wanted Outcome
c={ 7; 'B' ; 5 ; 6; 'A' ; 'A'; ; 'A'};
  3 Comments
Dora de Jong
Dora de Jong on 19 Mar 2021
Sorry the c had a typo. Here is the good one.
c={ 7; 'B' ; 5 ; 6; 'A' ; 'A'; 'A'};
No this is not a homework question. It is simplified version of a piece of script I'm working on.
Dora de Jong
Dora de Jong on 19 Mar 2021
@Jan I am think now on something like this.
a={'A'; 'B' ; 5 ; 6; 'A' ; 'A'; 'B'};
b={ 7; 'B' ;'A' ;'B'; 'A' ; 'B' ; 'A'}
c=cell(7,1);
for s=1:7
if a(s,1)=='A' && a(s,2)=='A'
c(s)='A'
elseif b(s,1)=='B' && b(s,2)=='B'
c(s)='B'
elseif b(s,1)=='A' && b(s,2)=='B'
c(s)='A'
elseif b(s,1)=='B' && b(s,2)=='A'
c(s)='A'
else
c(s) = %value
end
end

Sign in to comment.

Accepted Answer

Jan
Jan on 19 Mar 2021
Edited: Jan on 19 Mar 2021
a = {'A'; 'B' ; 5 ; 6; 'A' ; 'A'; 'B'};
b = { 7; 'B' ;'A' ;'B'; 'A' ; 'B' ; 'A'};
c = cell(size(a)); % Pre-allocation
isNum_a = cellfun('isclass', a, 'double');
isNum_b = cellfun('isclass', b, 'double');
sameChar = strcmp(a, b); % replies FALSE, if one is a number
c(isNum_a) = a(isNum_a);
c(isNum_b) = b(isNum_b); % prefer b if both are numbers [EDITED, Typo fixed]
c(sameChar) = a(sameChar); % or b(sameChar)
c(~sameChar & ~isNum_a & ~isNum_b) = {'A'};
  6 Comments
Dora de Jong
Dora de Jong on 23 Mar 2021
Edited: Jan on 23 Mar 2021
I am wokring on the script we discussed yesterday. Now I'am making the script for more strings than two. So not only:
a = {'A'; 'B' ; 5 ; 6; 'A' ; 'A'; 'B'};
b = { 7; 'B' ;'A' ;'B'; 'A' ; 'B' ; 'A'};
But a lot more of these.
Do you have a idea how we can make the part below, if we have more strings than two.
sameChar = strcmp(a, b);
c(sameChar) = a(sameChar);

Sign in to comment.

More Answers (0)

Categories

Find more on Historical Contests in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!