how to do this calculation not by 'for' cycle?

1 回表示 (過去 30 日間)
vx2008
vx2008 2015 年 12 月 15 日
コメント済み: Guillaume 2015 年 12 月 15 日
I have the below data:
data =[...
1.0000 1.0000 1.0000 53.1100;...
1.0000 2.0000 2.0000 59.0900;...
2.0000 1.0000 2.0000 71.3100;...
2.0000 2.0000 1.0000 70.2400]
Now I want to get a 'variable'--Data as below:
Data=[53.11+59.09 53.11+71.31 53.11+70.24;
71.31+70.24 59.09+70.24 59.09+71.31]
I can get 'Data' by 'for' cycle function but I want to do this work by other better method.
The addition logic is that:
take column 2 of data for example, both data(1,2) and data(3,2) equal 1.0000, so add data(1,4) and data(3,4) to get Data(1,2).

採用された回答

Guillaume
Guillaume 2015 年 12 月 15 日
One possible way to do it:
data = [1 1 1 53.1100
1 2 2 59.0900
2 1 2 71.3100
2 2 1 70.2400];
%first split data into two matrices for easier referencing:
rowdest = data(:, 1:end-1);
rowvals = data(:, end);
%second create matrix of column indices
coldest = repmat(1:size(rowdest, 2), size(rowdest, 1), 1);
%third use accumarray to compute the sum:
newdata = accumarray([rowdest(:) coldest(:)], repmat(rowvals, size(rowdest, 2), 1))

その他の回答 (1 件)

Stephen23
Stephen23 2015 年 12 月 15 日
編集済み: Stephen23 2015 年 12 月 15 日
This is easy using accumarray:
inp = [1,1,1,53.1100;1,2,2,59.0900;2,1,2,71.3100;2,2,1,70.2400]
out(:,3) = accumarray(inp(:,3),inp(:,4));
out(:,2) = accumarray(inp(:,2),inp(:,4));
out(:,1) = accumarray(inp(:,1),inp(:,4))
and the result is:
out =
112.20 124.42 123.35
141.55 129.33 130.40
and your example output is:
>> [53.11+59.09,53.11+71.31,53.11+70.24;71.31+70.24,59.09+70.24,59.09+71.31]
ans =
112.20 124.42 123.35
141.55 129.33 130.40
  1 件のコメント
Guillaume
Guillaume 2015 年 12 月 15 日
If data is always three columns of indices + one column of number, this works. If the size of data is not fixed, my answer is more generic.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by