Filter löschen
Filter löschen

Two cells merged together with different conditions

1 Ansicht (letzte 30 Tage)
Dora de Jong
Dora de Jong am 19 Mär. 2021
Bearbeitet: Jan am 23 Mär. 2021
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 Kommentare
Dora de Jong
Dora de Jong am 19 Mär. 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 am 19 Mär. 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

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Jan
Jan am 19 Mär. 2021
Bearbeitet: Jan am 19 Mär. 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 Kommentare
Dora de Jong
Dora de Jong am 23 Mär. 2021
Bearbeitet: Jan am 23 Mär. 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);
Dora de Jong
Dora de Jong am 23 Mär. 2021
I found allready a solution

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Historical Contests finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by