Using a for loop to iterate over rows of a matrix?
95 次查看(过去 30 天)
显示 更早的评论
So I am trying to create a for loop that runs rows of a matrix through a funtction. This is the function I have created:
function [Re, flow_type] = Reynolds(p,v,L,u)
Re=(p*v*L)/u
if Re<1000
flow_type = "Laminar"
elseif Re>10000
flow_type = "Turbulent"
else
flow_type = "Transition"
end
end
I have a 3x4 matrix callled flowData where column 1 is p, column 2 is v, column 3 is L, and column for is u. I have to use a for loop to iterate over the rows of the matrix, and then call the function for each row and print the results.
I have tried a couple things, but here is my current code. I am just not sure how to iterate over the rows of the matrix and use that in the function.
row1=flowData(1,:)
for i=1:row1
Re = Reynolds(p*v*L)/u;
flow_type =string([]);
end
0 个评论
回答(2 个)
Dongliang Lu
2019-9-28
Hope this helps:
for i=1:size(flowData,1)
[Re,flow_type] = Reynolds(p(i,1),v(i,2),L(i,3),u(i,4));
sprintf('%s',flow_type);
end
0 个评论
dpb
2019-9-28
Alternatively, consider vectorizing the function instead of using a loop...
function [Re, flow_type] = Reynolds(p,v,L,u)
Re=(p.*v.*L)./u;
flow_type=regime(Re);
function type=regime(Re)
flow_types=["Laminar","Transition","Turbulent"]; % regime types
fnRgm=@(Re) interp1([0 1000-eps(1000) 1000 10000 10000+eps(10000) realmax],[1 1 2 2 3 3],Re,'previous');
type=flow_types(fnRgm(Re));
end
end
0 个评论
另请参阅
类别
在 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!