Multiplying each cell in an array by a column vector

1 回表示 (過去 30 日間)
Stacy Genovese
Stacy Genovese 2022 年 5 月 2 日
編集済み: Rik 2022 年 5 月 2 日
I have this code:
p_m = ones(m,N) .* 1/m;
for i = 1:N
temp{i} = cellfun(@(x,y) x.*y, p_m(:,i),energy_self{i}(:), 'UniformOutput',false);
end
self_energy = sum(sum([temp{:}]))
where energy_self is a 1xN cell array with each cell having a mxm matrix. I want to multiply cell 1 by the first column of p_m, cell 2 by the second column, etc. Then when that's done, add all the elements of the cell array into one number.
Any ideas?
Thanks in advance.

採用された回答

Rik
Rik 2022 年 5 月 2 日
編集済み: Rik 2022 年 5 月 2 日
You should use a loop. That makes it a lot easier to write the indexing you need, and it will be faster.
Matrix operations are the fastest in Matlab, followed by loops, followed by loops obfuscated by cellfun or arrayfun. One exception: the legacy syntax of cellfun (e.g. cellfun('isempty',C)) can be faster than a loop.
  3 件のコメント
Stacy Genovese
Stacy Genovese 2022 年 5 月 2 日
This is what i did:
for residue = 1:N
temp{residue} = p_m(:,residue) .* energy_self{residue};
end
self_energy = sum(sum([temp{:}]));
Thanks so much!
Rik
Rik 2022 年 5 月 2 日
編集済み: Rik 2022 年 5 月 2 日
You're welcome. If I solved your issue, please consider marking it as accepted answer. That will help future users find a solution more quickly.
You could also consider doing the sumation inside the loop already:
self_energy=0;
for residue = 1:N
temp = p_m(:,residue) .* energy_self{residue};
self_energy = self_energy + sum(temp(:));
end

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by