If then question, find data in another column

Hi everybody,
I have a cell-array AA like this: AA = {[1;1;1;5;5;5;3;3;3],[40;40;70;70;20;20;20;10;10],[270;270;270;270;270;330;330;330;300]}. Now I need to find for a specific value in AA{3} (e.g. 270) and a specific value in AA{2} (e.g. 40) the sum(AA{1} == 1).
For example, I have five values == 270 in A{3} and only two of them match with the value 40 in A{2}. For those two values the sum(AA{1} == 1) == 2. I tried to do something like:
for j = length(AA{1})
if(AA{3}(j) == 270 && AA(2) == 40)
val = sum(AA{1}(j) == 1);
else
val2 = sum(AA{1}(j) == 5)+sum(AA{1} == 3);
end
end
Of course it doesn't work...Thank you for your help!

Answers (1)

Stephen23
Stephen23 on 19 Sep 2018
Edited: Stephen23 on 19 Sep 2018
You need to forget about using low-level loops to solve every little task and learn how to use MATLAB indexing to vectorize your code. Working with a numeric matrix is much easier than fiddling around with a cell array, so I put your data into one matrix M:
>> M = [AA{:}]
M =
1 40 270
1 40 270
1 70 270
5 70 270
5 20 270
5 20 330
3 20 330
3 10 330
3 10 300
>> idx = M(:,3)==270 & M(:,2)==40;
>> sum(M(idx,1))
ans = 2

2 Comments

Thank you for the suggestion, it was extremely helpful.
The problem is that I can use MATLAB indexing only if I want to work with a couple of values. The size of my M is actually 2054 3. That's why I was using a loop.
"The problem is that I can use MATLAB indexing only if I want to work with a couple of values."
I doubt that you need to use a loop, most likely there are simpler ways using indexing. Can you please give an example with some more values, showing both the input and output arrays.

This question is closed.

Tags

Asked:

on 19 Sep 2018

Closed:

on 20 Aug 2021

Community Treasure Hunt

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

Start Hunting!