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

35 views (last 30 days)
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?

Answers (1)

Peng Li
Peng Li on 27 Mar 2020
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 Comments
Sabine Merzoug
Sabine Merzoug on 28 Mar 2020
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)

Sign in to comment.

Categories

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

Community Treasure Hunt

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

Start Hunting!

Translated by