user3333799
user3333799

Reputation: 15

for loop to create a column vector

I would like to create a column vector with a function where one variable is fixed and one changes. I have the following code in MATLAB:

y3=ones(100,1)
for n=2:100
u3 = ((y3).^(1-n)-1)/(1-n);
end

where u3 is the function. y3 is a 100,1 vector and is constant. n is the changing variable. The output of my loop should be a column vector which shows in every row a changed n like this

row 1 ((y3).^(1-2)-1)/(1-2);
row 2 ((y3).^(1-3)-1)/(1-3);
row 3 ((y3).^(1-4)-1)/(1-4);
... and so on

The code doesnt work properly, please help me to find the mistake.

Upvotes: 0

Views: 455

Answers (1)

Nitish
Nitish

Reputation: 7186

1) There is no need to store y3 as a constant array. If you know y3 is a constant, just use y3=1 and (y3^(1-n)-1)/(1-n);

2) During every execution of the loop, u3 is being over-written. If you want to collect it, you might want to do something like u3(n-1)=((y3).^(1-n)-1)/(1-n);.

3) This can potentially be optimized by vectorizing the operation and getting rid of the for loop. Have you considered that?

Something along the lines of:

n = 2:100;
y3 = 1;
u3 = (y3.^(1-n)-1)./(1-n);

Upvotes: 1

Related Questions