Hi, I am struggling to apply my fun to a loop. Any tip? Here is my code:
function T=totalflow(x,N)
T(:)=x(1:N)+x(N+1:2*N);
end
%saved as totalflow.m
and main program:
inFlow = rand(10,3);
x0 = [inFlow; zeros(size(inFlow))];
[N,M] = size(inFlow);
T=totalflow(x0,N);
% this works for only one column on inFlow. I want to get T[10,3] like:
for i=1:M
T(:,i)=totalflow(x0(:,i),N);
end
%this does not work. Any tip? Thanks

 採用された回答

Stephen23
Stephen23 2018 年 5 月 25 日
編集済み: Stephen23 2018 年 5 月 25 日

0 投票

function out = totalflow(x,N)
out = x(1:N) + x(N+1:2*N);
end
and
M = rand(10,3);
[R,C] = size(M);
T = nan(R,C);
X = [M;zeros(R,C)];
for k = 1:C
T(:,k) = totalflow(X(:,k),R);
end

1 件のコメント

sensation
sensation 2018 年 5 月 25 日
Thanks! So the trick was in preallocating:) I used T = zeros([R,C]); instead of T = nan(R,C). The second did not run on my matlab version (2016a). Thanks!
Cheers

サインインしてコメントする。

その他の回答 (1 件)

Torsten
Torsten 2018 年 5 月 25 日

0 投票

Use
% T=totalflow(x0,N);
instead of
T=totalflow(x0,N);
Best wishes
Torsten.

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2018 年 5 月 25 日

コメント済み:

2018 年 5 月 25 日

Community Treasure Hunt

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

Start Hunting!

Translated by