Multiply the vector organs
이전 댓글 표시
How to multiply the vector parts without using a prod function
For example: s=[1 2 3 4], v=24
답변 (2개)
John D'Errico
2017년 12월 27일
편집: John D'Errico
2017년 12월 27일
You want to multiply s*v, so perform that multiplication, but without using the * operator? May I ask why you want to do such a silly thing, instead of just doing s*v?
As long as one of them is a scalar, then conv will suffice.
conv(s,v)
It will be slower, less efficient. It will serve absolutely no purpose.
(See the comments in case I was wrong in interpreting the ambiguous question.)
댓글 수: 5
Eran Shvartzman
2017년 12월 27일
John D'Errico
2017년 12월 27일
편집: John D'Errico
2017년 12월 27일
So you have been given two answers both sufficient to answer your question as posed. If you need to use an explicit loop, then that is your homework assignment.
If we do it for you, then you learn nothing, except how to con someone into doing your thinking for you. So why not make an effort? You will learn by making that effort, because it will force you to read the help for those tools, and to think about how they work. Of course, you will also find examples in the help docs.
If and when you really do have a question about MATLAB, then show what you did. Explain what your problems is, explain why you got stuck. You might get an answer then that is more likely to be of help, and more sympathy. But if you don't even try, how can I be sympathetic?
John D'Errico
2017년 12월 27일
편집: John D'Errico
2017년 12월 27일
IF Matt was correct and the goal is to not use prod to form the equivalent of v=prod(s), then this does not use prod, and uses a loop:
for i=1:1
v = cumprod(s); v = v(end);
end
Ok, that uses cumprod. If prod is out, then cumprod may be prohibited too. DRAT! So I need to be more creative?
for i=1:1
v = det(diag(s));
end
v
v =
24
Note that this survives even if one of the elements of s is zero.
It can also be done using conv.
for i=1:1
v = conv(conv(conv([1,s(1)],[1,s(2)]),[1,s(3)]),[1,s(4)]);
v = v(end);
end
v
v =
24
Of course, that last one is clumsy, because if s varies in length, it would not work as easily.
Note that this survives even if one of the elements of s is zero.
So, incidentally, does exp(sum(log(s))).
>> v=exp(sum(log([0,1,2,3])))
v =
0
Negative numbers work, too.
John D'Errico
2017년 12월 27일
Good point!
for i=1:4
v=exp(sum(log(s)));
end
댓글 수: 1
John D'Errico
2017년 12월 27일
You may be right here. the request may be to write v=prod(s), without use of prod, instead of forming the product s*v.
카테고리
도움말 센터 및 File Exchange에서 Operations on Numbers에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!