Reputation: 309
A = [0 0 1 2 3 4 5 0 0;
1 2 3 4 5 0 0 0 0;
0 0 0 1 2 3 4 5 0;
0 0 0 0 1 2 3 4 5]
and then from the above matrix, I want to account value 1 which is not the same column with value >3. but it is not problem if only has one value which is the same column with value "1".
so i wish the result is
res = 2.
they are value "1" which is in first row and second row.
so what is its code to solve it?? thanks..
Upvotes: 0
Views: 60
Reputation: 1039
If I follow what you're asking about here. You'd like to be able to know if a given column contains a value of 1
and no values 3
or greater.
This should get you started:
for n = 1:size(A,2)
if(~numel(find(A(:,n)>2)) && numel(find(A(:,n)==1)))
disp('found')
end
end
To break down what is happening here.
The loop is designed to go through each column in the matrix A
.
numel
returns the number of elements that are in the matrix within the parens ().
find
will return the index(s) of the element(s) that match the comparison criteria. In the first case we're looking for elements greater than 2. In the second elements that are equal to 1. Since we are only sending a column of values (a vector) we will only get a vector in return to the numel
call.
numel
simply counts the number of items in that vector and returns that number. If the vector is empty the number is 0. I also use the fact that the if
will interpret a 0 from numel
as false so you won't execute what is within the if
even if there are no values in the column greater than 2.
So if you want to know the number of 1
s in the column you simply use the numel(find(A(:,n)==1)) part of the if statement.
Upvotes: 1