addition of one column with certain condition in a

2019-09-29 11:04发布

问题:

Possible Duplicate:
addition of one column with certain condition in another colum, like sumifs of excel

here i want to count the no of 2nd column, with the same conditions in column 1, i m dictating here again,

A=[1 2;2 3;3 4;3 2;4 3;5 4;5 2;6 3;7 2;8 3]

now i want to count no of 2, 3 and 4 in column2, condition is that when column 1 ranges from 0 to 3, 3 to 6, 6 to 9, 9 to 12 like that.

answer is like that

ranges no2, no3, no4

0 to 3-- 2-----1-------1

3 to 6---1------2-------1

6 to 9-- --1-----1------0

help me,,,, waiting for your reply..

回答1:

With MATLAB you can use logical indexing meaning that you can filter a variable with any number of conditions. For example, if vec is any vector and you wish to know how many elements of vec are negative you can do the following,

% save the elements of vec which are negative
ind = vec < 0
% vec is a logical variable. Each element of vec lower that 0 is store as 1.
% to know how many elements of vec are smaller than 0
sum(ind)
% will tell you how many ones are there in ind, meaning the number of elements in vec which
% are smaller than 0

% Of course you can do the same all at once,
sum(vec < 0)
% and you can directly access the elements in the same way
vec(vec < 0)

So returning to your problem, you can use something like,

for i = 1:3:length(A)
    %print how many 2s,3s and 4s
    fprintf('%d to %d: %d, %d, %d\n',i,i+2,sum(A(i:i+2,2)==2),sum(A(i:i+2,2)==3),sum(A(i:i+2,2)==4))
end


回答2:

You could potentially do something like this:

for(n=1:size(A,1))
    if(A(n,1) >= 0 && A(n,1) < 3)
        % Do something
    elseif( ) % next test condition
        % Do something there.
    end 
end

Another option would be to use the for loop to go through your first column and using a switch statement to pull the appropriate action based on that input.

Update below:

for(n = 1:size(A,1))
    switch(mod(A(n,1),3))
        case 0 % this will be 0, 1, 2 in your column
            % code
        case 1
            etc...
    end
end

Info on modulus in matlab

Info on switch in matlab