Scott Rothbaum
Scott Rothbaum

Reputation: 3

Sum of all values in matrix (Matlab)

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!

Upvotes: 0

Views: 1230

Answers (1)

TroyHaskin
TroyHaskin

Reputation: 8401

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).

Upvotes: 2

Related Questions