how to sum of each row according to values values in given function
    1 vue (au cours des 30 derniers jours)
  
       Afficher commentaires plus anciens
    
  Here I have a matrix of five rows and six columns. I want sum of each row according to given function by using for loop.  
f(1)=15*x(1)+20*x(2)+30*x(3)+25*x(4)+40*x(5)+35*x(6);
f(2)=20*x(1)+23*x(2)+21*x(3)+24*x(4)+28*x(5)+27*x(6);
f(3)=16*x(1)+24*x(2)+22*x(3)+23*x(4)+20*x(5)+17*x(6);
f(4)=25*x(1)+26*x(2)+27*x(3)+28*x(4)+29*x(5)+30*x(6);
  where x shows the element number in each row, such as six columns in below matrix               
  1  0  1  0  0  1
  1  0  0  1  0  1
  1  0  0  0  1  1
  1  0  0  1  1  1
  0  1  1  0  0  1
4 commentaires
Réponse acceptée
  Rik
      
      
 le 12 Mar 2019
        
      Modifié(e) : Rik
      
      
 le 12 Mar 2019
  
      You can do something like the code below. You could use a for loop instead of the call to cellfun, but as you can see, you don't really need an explicit loop here.
data=[1  0  1  0  0  1
    1  0  0  1  0  1
    1  0  0  0  1  1
    1  0  0  1  1  1
    0  1  1  0  0  1 ];
data_cell=mat2cell(data,ones(1,size(data,1)),size(data,2)); %group data by row
f_cell=cellfun(@MyFunction,data_cell,'UniformOutput',0);    %apply function to each row
f=cell2mat(f_cell);                                         %convert results back to an array
function f=MyFunction(x)
f(1)=15*x(1)+20*x(2)+30*x(3)+25*x(4)+40*x(5)+35*x(6);
f(2)=20*x(1)+23*x(2)+21*x(3)+24*x(4)+28*x(5)+27*x(6);
f(3)=16*x(1)+24*x(2)+22*x(3)+23*x(4)+20*x(5)+17*x(6);
f(4)=25*x(1)+26*x(2)+27*x(3)+28*x(4)+29*x(5)+30*x(6);
end
Plus de réponses (1)
  Stephen23
      
      
 le 12 Mar 2019
        Simpler:
>> X = [1,0,1,0,0,1;1,0,0,1,0,1;1,0,0,0,1,1;1,0,0,1,1,1;0,1,1,0,0,1]
X =
   1   0   1   0   0   1
   1   0   0   1   0   1
   1   0   0   0   1   1
   1   0   0   1   1   1
   0   1   1   0   0   1
>> M = [15,20,30,25,40,35;20,23,21,24,28,27;16,24,22,23,20,17;25,26,27,28,29,30]
M =
   15   20   30   25   40   35
   20   23   21   24   28   27
   16   24   22   23   20   17
   25   26   27   28   29   30
>> sum(permute(M,[3,1,2]).*permute(X,[1,3,2]),3)
ans =
    80    68    55    82
    75    71    56    83
    90    75    53    84
   115    99    76   112
    85    71    63    83
0 commentaires
Voir également
Catégories
				En savoir plus sur Data Type Conversion dans Help Center et File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!



