How can I obtain a certain value from the function 'find' from a 3x2 cell?
1 view (last 30 days)
Show older comments
Pietro Fedrizzi
on 21 Oct 2021
Commented: Pietro Fedrizzi
on 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 Comments
dpb
on 22 Oct 2021
Just repeating the same unclear verbiage doesn't help -- SHOW us the input and corresponding output expected.
Accepted Answer
Dave B
on 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
More Answers (0)
See Also
Categories
Find more on Logical 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!