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

2 次查看(过去 30 天)
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 个评论
KALYAN ACHARJYA
KALYAN ACHARJYA 2019-12-27
编辑:KALYAN ACHARJYA 2019-12-27
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 2019-12-28
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.

请先登录,再进行评论。

回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by