How to add values into a vector with for loop in a function
14 次查看(过去 30 天)
显示 更早的评论
Hi,
I want to add values for every loop of t. The function looks like this:
function[SOC_a] = test1(P_batt, SOC_a,E_0,t)
for i=1:1439
while i>=t
while SOC_a(i) <= 0.5
SOC_a(i+1) = SOC_a(i) + 1/(E_0) * P_batt/60;
return
end
end
end
end
And the "mainscript" looks like this:
SOC_a= zeros(1,1440);
P_batt=50;
E_0=1000;
for t=1:1440
SOC_a(1)=0.2;
[SOC_a(t)] = test1(P_batt, SOC_a(t),E_0,t);
end
disp(SOC_a)
The value of SOC_a is supposed to increase for every loop, but when I run the script it says that "In an assignment A(:) = B, the number of elements in A and B must be the same." but I don't understand why. SOC_a is always a 1x1440 vector. It works when there is no function and everything is written in the main code. But I want to know why it doesnt work when it's in the function.
Can anybody help me please?
0 个评论
回答(1 个)
Peng Li
2020-3-27
It looks that in your function test1, the second parameter SOC_a is supposed to be a vector.
While in your main function, when you call test1, you only pass a scalar to it by SOC_a(t). This scalar is extended in test1, and resulted in a vectorized SOC_a, which you are trying to assign it to a scalar SOC_a(t).
Your code is quite twisted. I guess you only want to output the last element of SOC_a in your function test1?
3 个评论
Peng Li
2020-3-27
function y = test1(P_batt, SOC_a, E_0, t)
for i=1:1439
while i>=t
while SOC_a(i) <= 0.5
SOC_a(i+1) = SOC_a(i) + 1/(E_0) * P_batt/60;
return
end
end
end
y = SOC_a(end);
end
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Testing Frameworks 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!