how to sum of each row according to values values in given function

조회 수: 2 (최근 30일)
Asad Abbas
Asad Abbas 2019년 3월 12일
답변: Stephen23 2019년 3월 12일
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
Asad Abbas
Asad Abbas 2019년 3월 12일
For f(1) f(2) f(3) f(4)
1 0 1 0 0 1 80 68 55 82
1 0 0 1 0 1 75 71 56 83
1 0 0 0 1 1
1 0 0 1 1 1
0 1 1 0 0 1
Sum from f(1) are of those whose value is 1 in table.

댓글을 달려면 로그인하십시오.

채택된 답변

Rik
Rik 2019년 3월 12일
편집: Rik 2019년 3월 12일
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

추가 답변 (1개)

Stephen23
Stephen23 2019년 3월 12일
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

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by