How to multiply different elements of a vector(with no value stored) inside a for loop to generate an equation.

1 view (last 30 days)
I want to repeatedly add one form of the equation i times, in this I want constants as f(1),f(2)... and variables x1, x2...y1,y2...z1,z2...So, the required outcome for i=1 should be g=f(1).*x1.^2+f(2).*y1+f(3).*z1 as seen by program below(not working). It is necessary for its use with nlinfit.
I am trying to implement it using for loop with null vector(supposedly wrong approach). I have also tried declaring it as f(1)=[]... it also gives an error "Deletion requires an existing variable". It works if I use f as a symbol like x,y or z but that will be useless for me.
Please give me a solution to the problem addressed not the problems in my solution. Thanks :)
x=sym('x',[1 3]);
y=sym('y',[1 3]);
z=sym('z',[1 3]);
f=[]; %first way to declare null vector
%f=int16.empty(3,0); %second way to declare null vector
g=0;
a=1;
for i=1:1:3
g=g+f(i).*x(i).^2+f(i+1).*y(i)+f(i+2).*z(i);
a=a+3;
end
  5 Comments
KALYAN ACHARJYA
KALYAN ACHARJYA on 27 Dec 2019
Edited: KALYAN ACHARJYA on 27 Dec 2019
f=[];
If you multiply it with any,still it reflects a null vector. In this case there is no meaning of f(i) within loop iteration, which is f(1), f(2)...so on.
Vijay Shekhawat
Vijay Shekhawat on 28 Dec 2019
I clearly get it f=[] will not work, so please stop pointing at it again and again. Try to move ahead, I just want to add an equation of this form n times.
x=sym('x',[1 3]);
%How to declare f?? It should be a vector f(1), f(2) ...
n=3
g=0
for i=1:n
g=g+f(i).*x(i);
end
g
The above should return f(1).*x1+f(2).*x2+f(3).*x3.

Sign in to comment.

Answers (0)

Categories

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

Products

Community Treasure Hunt

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

Start Hunting!