For Loop / Sum of Equation

Hi I am trying to figure the best way to write the sum of an equation from j=1 to j=100 and have the answers show up in the workspace. Right now in the workspace I only get Xj = 100. But I want a 1x100 matrix in the workspace. This is probable really simple but not sure how to do it
Thanks
My code:
for j = 1:100;
xj=j
end

Answers (1)

madhan ravi
madhan ravi on 19 Oct 2018
Edited: madhan ravi on 19 Oct 2018
X = zeros(1,100) %preallocation for speed
for j = 1:100 %an example
X(j) = j; %saves X in each element to avoid overwriting
end
X
Remark : (j) inside loop is called as indexing which prevents overwriting in a loop

6 Comments

madhan ravi
madhan ravi on 19 Oct 2018
Edited: madhan ravi on 19 Oct 2018
if something is not clear let know
G
G on 19 Oct 2018
Could this work too?
syms j
Xj_sum = sum(subs(j^2, j, 1:100))
Xj_symsym = symsum(j^2, j, 1, 100);
Seems to work
you are asking or you sorted it out?
G
G on 19 Oct 2018
I am asking
Maybe you want this?
for j = 1:100 %an example
X(j) = j.^2; %saves X in each element to avoid overwriting
end
cumsum(X)
It’s possible try the following
syms j
for i=1:100
Xj_symsym(i) = symsum(j^2, j, 1, i);
end
Xj_symsym
Xj_symsym = double(Xj_symsym)
is this what you are looking for?

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

G
G
on 19 Oct 2018

Edited:

on 19 Oct 2018

Community Treasure Hunt

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

Start Hunting!