How can I obtain a certain value from the function 'find' from a 3x2 cell?
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Pietro Fedrizzi
le 21 Oct 2021
Commenté : Pietro Fedrizzi
le 22 Oct 2021
I need a certain variable "a" to be equal to either 1,2 or 3 according to two previous selection "Firstselection" and "Secondselection" which algo go from 1 to 3.
I have a 3x2 cell Comb = [1,2; 2,3; 1,3]. I have to assign "a" to a find function so that when Firstselection = 1 & Secondselection = 2 (and viceversa), a = 1, Firstselection = 2 & Secondselection = 3 (and viceversa), a = 2 and Firstselection = 1 & Secondselection = 3 (and viceversa), a = 3, all based on the cell Comb. I already solved it with an if cycle but now I need to apply the function find to the cell to obtain a certain value of "a" according to my 2 selections. I cannot change the cell.
7 commentaires
dpb
le 22 Oct 2021
Just repeating the same unclear verbiage doesn't help -- SHOW us the input and corresponding output expected.
Réponse acceptée
Dave B
le 21 Oct 2021
I think you're asking how to search for the index of a row in a matrix based on multiple columns (although you have a cell array, you can just convert that to start).
You'll want to think about a few 'special' cases: what if it isn't found? What if it's found in more than one place? ismember does a nice job if you're not concerned with the multiple result issue:
comb={1,2;3,4;1,3};
comb_mat=cell2mat(comb);
target=[1 2];
[~,wherefound]=ismember(target,comb_mat,'rows')
target=[3 4];
[~,wherefound]=ismember(target,comb_mat,'rows')
target=[1 3];
[~,wherefound]=ismember(target,comb_mat,'rows')
target=[12 13];
[~,wherefound]=ismember(target,comb_mat,'rows') % wherefound will be 0 if not found
comb={1,2;3,4;1,3;1,2};
comb_mat=cell2mat(comb);
target=[1 2];
[~,wherefound]=ismember(target,comb_mat,'rows') % wherefound will be the first index if multiple occurrences
Otherwise you can combine find with an &:
comb={1,2;3,4;1,3};
comb_mat=cell2mat(comb);
target=[1 2];
find(comb_mat(:,1)==target(1) & comb_mat(:,2)==target(2))
target=[3 4];
find(comb_mat(:,1)==target(1) & comb_mat(:,2)==target(2))
target=[1 3];
find(comb_mat(:,1)==target(1) & comb_mat(:,2)==target(2))
target=[12 13];
find(comb_mat(:,1)==target(1) & comb_mat(:,2)==target(2)) % find will return empty if not found
comb={1,2;3,4;1,3;1,2};
comb_mat=cell2mat(comb);
target=[1 2];
find(comb_mat(:,1)==target(1) & comb_mat(:,2)==target(2)) % find will return both indices if multiple results are found
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!