0
votes

So I'm trying to create a matlab function that takes two inputs, a matrix and a value, and returns the sum of all values in the matrix except for all instances of the given value. So far this is the code I have written:

function [total] = sumAllExcept(matrix, except)
    total = 0;
    for i = 1:size(matrix, 1)
        for k  = 1:size(matrix, 2)
            if(matrix(i, k) ~= except)
                total = total + matrix(i,k);
            end
        end
    end
end

The error message that I am receiving when trying to run the program is: " Undefined function 'sumAllExcept' for input arguments of type 'double'. " I would greatly appreciate it if you would show me whats wrong with this and fix anything that you can. Thank you!

1
So that answer to this problem is a one liner? Just say sum(sum(matrix ~= except)) takes care of everything for me? Sorry about my silly questions. I really don't get matlab compared to other programming languagesScott Rothbaum
Oh wait! I got that wrong! I thought you were looking for the count! My apologies.Divakar

1 Answers

2
votes

Sum the array after filtering out except using logical indexing:

total = sum(matrix( matrix ~= except ));

The result of using the logical index matrix ~= except on matrix returns a column vector, so only one sum is required.


The error "Undefined function 'sumAllExcept' for input arguments of type 'double'." is likely due to the function not being on MATLAB's path or the function name sumAllExcept not matching the filename (i.e., sumAllExcept.m).