1

次のコードがあります。

L_sum = zeros(height(ABC),1);
for i = 1:height(ABC)
     L_sum(i) = sum(ABC{i, ABC.L(i,4:281)});
 end

ここに私のテーブル: ここに画像の説明を入力

問題: 私の sum 関数は、日付ごとに行全体の値 (col. 4-281) を合計しますが、特定の日付について、ヘッダーが ABC.L のセル配列にあるセルのみを追加したいと考えています。


X = ABC.L{1, 1}; 与える(抜粋):

ここに画像の説明を入力


赤い矢印: sum 関数が参照しているもの (同じ日付の L)。

緑の矢印: 私が今参照しようとしているもの (前の日付の L)。 ここに画像の説明を入力

ご協力いただきありがとうございます

4

2 に答える 2

1

一般に、matlab では、選択的な合計などの単純な操作を行うために for ループを使用する必要はありません。例:

Data=...
    [1 2 3;
    4 5 6;
    7 8 9;
    7 7 7];

NofRows=size(Data,1);
RowsToSum=3:NofRows;
ColToSum=[1,3];
% sum second dimension 2d array
Result=sum(Data(RowsToSum,ColToSum), 2)

% table mode
DataTable=array2table(Data);
Result2=sum(DataTable{RowsToSum,ColToSum}, 2)
于 2017-01-04T17:32:42.070 に答える
0

これを行うには、最初に合計する列を抽出してから合計する必要があります。

% some arbitrary data:
ABC = table;
ABC.L{1,1} = {'aa','cc'};
ABC.L{2,1} = {'aa','b'};
ABC.L{3,1} = {'aa','d'};
ABC.L{4,1} = {'b','d'};
ABC{1:4,2:5} = magic(4);
ABC.Properties.VariableNames(2:5) = {'aa','b','cc','d'}

% summing the correct columns:
L_sum = zeros(height(ABC),1);
col_names = ABC.Properties.VariableNames; % just to make things shorter
for k = 1:height(ABC)
    % the following 'cellfun' compares each column to the values in ABC.L{k},
    % and returns a cell array of the result for each of them, then
    % 'cell2mat' converts it to logical array, and 'any' combines the
    % results for all elements in ABC.L{k} to one logical vector:
    col_to_sum = any(cell2mat(...
        cellfun(@(x) strcmp(col_names,x),ABC.L{k},...
        'UniformOutput', false).'),1);
    % then a logical indexing is used to define the columns for summation:
    L_sum(k) = sum(ABC{k,col_to_sum});
end
于 2017-01-04T21:50:53.850 に答える