Help to transform math formula to matlab

Hello,
I am trying to transform this formula into matlab, but I can't use a for/while loop. X is an array with dimension n and every position receives this sum.
I tried like this, but I couldn't remove the loop here, can I achieve this without a loop?
I also tried to use arrayfun, but without success because every position of the array was receiving the same value.

댓글 수: 7

Dave B
Dave B 2021년 11월 14일
Is there are part of the sum that you can pull out?
(is sum(100*j) different from 100*sum(j)?)
Matthew Lima
Matthew Lima 2021년 11월 14일
I'm sorry, I really let that pass. So I can remove the log(i) from sum, right?
Dave B
Dave B 2021년 11월 14일
That sounds like a good idea to me!
Matthew Lima
Matthew Lima 2021년 11월 14일
Thank you!
There is a way of achieving that without a loop?
Dave B
Dave B 2021년 11월 14일
There sure is! Break it down, now that you've got the i part out of the sum, where would you think you need a loop?
Matthew Lima
Matthew Lima 2021년 11월 14일
Thank you so much Dave, I am new to Matlab i didn't realize how simple it is.
Thank's for the clear explanation.
Dave B
Dave B 2021년 11월 14일
편집: Dave B 2021년 11월 15일
Ah I was trying to avoid doing it for you so that you could feel the satisfaction :) Glad it feels simple, hope it stays that way as you delve deeper!
note this is the simplified version of what you wrote:
x = log(1:n) * sum(exp((1:m).^2))

댓글을 달려면 로그인하십시오.

답변 (1개)

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2021년 11월 15일
Using the vectorization:
format long
m=5;
jj=1:m;
XSum1 = sum(log(jj).*exp(jj.^2))
XSum1 =
1.158997425794889e+11
% Or alternatively
Xs = log(jj).*exp(jj.^2);
XSum2=sum(Xs)
XSum2 =
1.158997425794889e+11
% Sum stepby-step:
cumsum(Xs)
ans = 1×5
1.0e+11 * 0 0.000000000378446 0.000000089399921 0.000123277048990 1.158997425794889

댓글 수: 1

Note that i and j are not the same in the question, the correct answer here is:
x = log(1:n) * sum(exp((1:m).^2))
as discussed in the comments above.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2021년 11월 14일

댓글:

2021년 11월 15일

Community Treasure Hunt

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

Start Hunting!

Translated by