How to make the sum of all elements?
    10 visualizzazioni (ultimi 30 giorni)
  
       Mostra commenti meno recenti
    
Hi,
M=10;
I have a matrix M=mxn and I want the sum of all elements, for n and m from 1 to 10.
My question is why this:
    for ii=1:M
        for ij=1:M
            A=sum(M(ii,ij));
        end
    end
does not give the same result as:
    A= sum(M,'all');
Thanks in advance for your reply.
0 Commenti
Risposta accettata
  madhan ravi
      
      
 il 29 Nov 2018
        
      Modificato: madhan ravi
      
      
 il 29 Nov 2018
  
      The result is not the same because you are summing up a scalar in  each iteration thats why example sum(5) ->5  so the one which you do after is the correct way to do that is sum(M,'all') which can also be written as sum(M(:)). Also ii should be from 1 to size(M,1) representing number of rows and ij from 1 to size(M,2) representing number of columns.
Example:
Code:
M=rand(3);  %your matrix
A=zeros(1,numel(M));  %preallocation
ctr=1;
for ii=1:size(M,1)
        for ij=1:size(M,2)
            A(ctr+1)=A(ctr)+(M(ii,ij));
            ctr=ctr+1;
        end
end
total_sum=max(A)
sum(M,'all') %if they are equal then the result obtained is correct
command window:
>> COMMUNITY
total_sum =
    4.8821
ans =
    4.8821
>> 
0 Commenti
Più risposte (0)
Vedere anche
Categorie
				Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

