Vectors and Sum operation

1 回表示 (過去 30 日間)
bondpen
bondpen 2018 年 3 月 19 日
コメント済み: bondpen 2018 年 3 月 19 日
Trying to use sum to figure about resistor formula, 1/[(1/r1)+1rn)] where n can be any number.
What i have come up with:
function R = scirpt(y)
R = 1/sum(1/(y));
end
Well be entering this:
scirpt([100,200,300]) should output 54.5455
if true
% code
end

採用された回答

John D'Errico
John D'Errico 2018 年 3 月 19 日
編集済み: John D'Errico 2018 年 3 月 19 日
R = 1/sum(1./y);
y is a vector. You want to divide EACH of the elements of y into 1. So you use the ./ operator, which is designed to solve element-wise operations. (Just like the .* and .^ operators.)
The other divide is a scalar/scalar operation, so / works fine there, although ./ would also be acceptable. That is:
R = 1./sum(1./y);
would also work.
Finally, there was no need to put a parens around y in your original line. So while it is fine to add additional parens if you are not sure you need them in some spot, too many parens that need not be there will only make things confusing, hard to read and debug.
  1 件のコメント
bondpen
bondpen 2018 年 3 月 19 日
Thanks for explaining why you need ./ operator. Thanks.

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

その他の回答 (0 件)

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by