How to add values into a vector with for loop in a function

14 ビュー (過去 30 日間)
Sabine Merzoug
Sabine Merzoug 2020 年 3 月 27 日
コメント済み: Sabine Merzoug 2020 年 3 月 28 日
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?

回答 (1 件)

Peng Li
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
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
Sabine Merzoug
Sabine Merzoug 2020 年 3 月 28 日
Ok, but I want SOC_a to change for every new t from 1 to 1440. If I write it like this, I get that the index exceeds matrix dimensions in the function.
SOC_a= zeros(1,1440);
P_batt=50;
E_0=1000;
for t=1:1440
SOC_a(1)=0.2;
[y] = test1(P_batt, SOC_a(t),E_0,t);
SOC_a(t)=y;
end
disp(SOC_a)

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeTesting Frameworks についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by