Hi Everyone,
I can't seem to understand why this function using a for loop doesn't seem to work.
function y = get_kV(n,t)
for k = 1:(n-1)
y = [t(1) t t(end)];
end
I tried it out:
kV = [0 4];
kV = get_kV(3, kV);
The answer should be kv = [0 0 0 4 4 4]
But it only goes through the iteration once and stops. I've written the exact same code in the Command Window and that works but why doesn't it work when I save it as a .m file?
Thanks for any help or advice. Cheers!

 採用された回答

Walter Roberson
Walter Roberson 2012 年 8 月 30 日

0 投票

You are overwriting "y" in every iteration of the loop. Only the final version of "y" is returned to the calling routine.

2 件のコメント

jljl
jljl 2012 年 8 月 30 日
Thanks for the fast reply, do you have any suggestions to correct it so that the function works correctly?
Jan
Jan 2012 年 8 月 30 日
@jljl: Please accept an answer, if it solves your problem sufficiently.

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

その他の回答 (1 件)

Jan
Jan 2012 年 8 月 30 日

2 投票

function y = get_kV(n,t)
y = repmat(t, n, 1);
y = y(:)'

カテゴリ

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

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by