Scripts works as main code but not as a function
3 次查看(过去 30 天)
显示 更早的评论
Hello All,
I've written a piece of script in my main code and it's working fine.
I'm trying to move it into a function to make my code more efficient, but it stops working and spits out the following error.
Error: Index exceeds the number of array elements (1).
Error in noflow_boundary (line 27)
lamdaWG(i) = lamdaO(i+Imax);
Here is my script within my main code:
for i=1:Imax*Jmax
if i <= Imax
lamdaWC(i) = 0;
else
lamdaWC(i) = lamdaO(i-Imax);
end
if mod(i,Imax) == 1
lamdaWD(i) = 0;
else
lamdaWD(i) = lamdaO(i-1);
end
if mod(i,Imax) == 0
lamdaWF(i) = 0;
else
lamdaWF(i) = lamdaO(i);
end
if i > (Imax*Jmax)-Imax
lamdaWG(i) = 0;
else
lamdaWG(i) = lamdaO(i+Imax);
end
end
And here is how I'm using it in function format:
function [lamdaWC,lamdaWD,lamdaWF,lamdaWG] = noflow_boundary(lamdaO,Imax,Jmax)
% No Flow Boundary Conditions
for i=1:Imax*Jmax
if i <= Imax
lamdaWC(i) = 0;
else
lamdaWC(i) = lamdaO(i-Imax);
end
if mod(i,Imax) == 1
lamdaWD(i) = 0;
else
lamdaWD(i) = lamdaO(i-1);
end
if mod(i,Imax) == 0
lamdaWF(i) = 0;
else
lamdaWF(i) = lamdaO(i);
end
if i > (Imax*Jmax)-Imax
lamdaWG(i) = 0;
else
lamdaWG(i) = lamdaO(i+Imax); % this is the line with the error occurs
end
end
end
And here's how I'm calling the function in my main code:
[lamdaWC(i),lamdaWD(i),lamdaWF(i),lamdaWG(i)] = noflow_boundary(lamdaO(i),Imax,Jmax);
Anyone has any idea why the error is popping out in the function and not main code? and how I can resolve it?
Thanking you in advance.
0 个评论
采纳的回答
Fangjun Jiang
2020-7-15
call it this way
[lamdaWC,lamdaWD,lamdaWF,lamdaWG] = noflow_boundary(lamdaO,Imax,Jmax);
更多回答(1 个)
Tanmay Das
2020-7-15
Hi,
I have the understanding that you are passing a single element i.e. lamdaO(i) as an argument but in order to execute your function, you may need to pass the whole array i.e. lamdaO. Also the return types are arrays so you may need to assign the return values of your function to arrays instead. The following code may be helpful for your understanding:
% function definition
function [lamdaWC,lamdaWD,lamdaWF,lamdaWG] = noflow_boundary(lamdaO,Imax,Jmax)
% No Flow Boundary Conditions
for i=1:Imax*Jmax
if i <= Imax
lamdaWC(i) = 0;
else
lamdaWC(i) = lamdaO(i-Imax);
end
if mod(i,Imax) == 1
lamdaWD(i) = 0;
else
lamdaWD(i) = lamdaO(i-1);
end
if mod(i,Imax) == 0
lamdaWF(i) = 0;
else
lamdaWF(i) = lamdaO(i);
end
if i > (Imax*Jmax)-Imax
lamdaWG(i) = 0;
else
lamdaWG(i) = lamdaO(i+Imax); % this is the line with the error occurs
end
end
end
% function call
[lamdaWC,lamdaWD,lamdaWF,lamdaWG] = noflow_boundary(lamdaO,Imax,Jmax);
Hope that helps!
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!