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

1 回表示 (過去 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 件のコメント
madhan ravi
madhan ravi 2019 年 3 月 12 日
Desired result example?
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 Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by