Info

この質問は閉じられています。 編集または回答するには再度開いてください。

Finding Nonzero Elements in a Vector

1 回表示 (過去 30 日間)
Sophie Culhane
Sophie Culhane 2020 年 9 月 20 日
閉鎖済み: MATLAB Answer Bot 2021 年 8 月 20 日
In a assignment I am working on, we are tasked with writing a MATLAB function that takes as input a nonempty vector v and returns the product of the nonzero elements in the vector. If there are no nonzero elements, a value of 1 is returned. As of now, I have a working program that calculates the correct answer, however it computes the product of all elements, instead of all nonzero elements. I am asking for help on how to make this simple change in my program. Below is what I have so far.
function prod = ex1(v)
%
%
vLength = length(v);
prod = 1;
CurrentPosition = 1;
for CurrentPosition = 1:vLength
prod = prod * v(CurrentPosition);
CurrentPosition = CurrentPosition + 1;
end
  1 件のコメント
Walter Roberson
Walter Roberson 2020 年 9 月 20 日
By the way, the code can be vectorized to less than 20 characters (excluding the "function" line.)

回答 (1 件)

James Tursa
James Tursa 2020 年 9 月 20 日
編集済み: James Tursa 2020 年 9 月 20 日
You need to wrap this statement with an if-test and only execute it if v(CurrentPosition) is non-zero:
prod = prod * v(CurrentPosition);
Also, get rid of the following line. You should not be manually altering the for-loop index variable within the loop:
CurrentPosition = CurrentPosition + 1;
You can get rid of this line also, since it doesn't actually accomplish anything useful.
CurrentPosition = 1;

この質問は閉じられています。

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by