Using a for loop to iterate over rows of a matrix?
조회 수: 101 (최근 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!