Write a function called halfsum that takes as input an at most two-dimensional matrix A and computes the sum of the elements of A that are in the diagonal or are to the right of it. example, the input is [1 2 3; 4 5 6; 7 8 9],the ans is 26
@Nadeem: this is exactly equivalent to the comment by Sai. Except that in your version, you use the sum function as a variable name. That is a bad idea, as it will lead to strange errors if you later try to use sum as a function.
Of all the inefficient loop-based approaches on this page, this appears to be the most wasteful by far. For every single element of the array, you calculate the sum of the entire array and then discard the result. The only sum that doesn't get discarded is the last one. As a consequence, the time required grows rapidly as the matrix size increases -- all for nothing.
Try feeding this a large array. For a 400x400 matrix, this takes roughly 1000x as much time as the other loop-based examples, and nearly 6000x as much time as @Sean de Wolski's concise and efficient answer. Would you dare to feed it a 4000x4000 matrix?
I believe that if you test more carefully, you will find that the failure is in the row vector case.
Suppose you have 1 x 3 vector. Then [a b] = size(M) woud be a=1, b=3. You have for n=1:1 and for m=1:3 . 1>1 is false, 1>2 is false, 1>3 is false, so the if n>m test always fails, so you never assign anything to summa.
I hope this clears your doubt. You did not tell function what to if there is n ==1 means there is column vector. I have made this correction. Now function works fine. Thanks
First we initialize the output summa. Second we assign s as the size of the matrix M . In fact , size(M) returns a vector with two values. The first value s(1) is the row number and the second value s(2) is the column number. The variable i is for the row indexes( from 1 to s(1)) and the variable j is for column indexes(from 1 to s(2)) . In every time where we find a value of the matrix which has a column index ( j ) higher or equal to the row index ( i ), we add this value to summa, and so over, until we find the total sum. If the condition (j>=i) is not true, the variable summa stays the same and doesn't change, that means : summa=summa .
I hope it's clear now . you can ask if there's something u r not convinced with
You can also select a web site from the following list:
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country
sites are not optimized for visits from your location.