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!