Using a for loop to iterate over rows of a matrix?

77 ビュー (過去 30 日間)
Brian Bowne
Brian Bowne 2019 年 9 月 28 日
回答済み: dpb 2019 年 9 月 28 日
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

回答 (2 件)

Dongliang Lu
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

dpb
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

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by