# How can I correctly use if and elseif?

3 ビュー (過去 30 日間)
gblmtc 2018 年 3 月 22 日
コメント済み: Stephen23 2018 年 3 月 22 日
Hi there! I'm a newbie on the Matlab and I just don't know how to write this function.
I have two inputs : t and toe
I have to calculate
tk = t-toe
if tk > 302400 tf = tk - 604800
if tk < -302400 tf tk + 604800
I created this function :
function [tk] = time(a)
a=t-toe;
if tk>302400; tf = tk-604800;
elseif tk<-302400; tf = tk+604800;
end
end
when I run this function I get this error.
% Undefined function 'time' for input arguments of type 'double'.
what does it mean "input arguments of type double"? what is the double there?
P.S: How can I learn more quickly this program? It seems a bit complicated for me considering I've never learnt programming before. Could I find some exercises to help me learn it?
##### 3 件のコメント1 件の古いコメントを表示1 件の古いコメントを非表示
KL 2018 年 3 月 22 日

Walter Roberson 2018 年 3 月 22 日
Notice by the way that used
a=t-toe;
Also, you have not defined toe.

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

### 採用された回答

Stalin Samuel 2018 年 3 月 22 日
create a file with below code
function [tf] = time(t,toe)
tk=t-toe;
if tk>302400; tf = tk-604800;
elseif tk<-302400; tf = tk+604800;
end
end
while saving the code you must use "time" as file name.
##### 2 件のコメントなしを表示なしを非表示
gblmtc 2018 年 3 月 22 日
Thanks Samuel! I applied your function, it works but it calculates just tk=t-toe. It doesn't either add or subtract 604800. Doesn't continue and do the if . Do you know why?
Stephen23 2018 年 3 月 22 日

@gblmtc: What sizes are t and toe ?
Why did you accept this answer if it does not do what you want?

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

### その他の回答 (1 件)

Stephen23 2018 年 3 月 22 日
I guess that some of the inputs are non-scalar, in which case you should use indexing:
function tk = time(t,toe)
tk = t-toe;
idx = tk>302400;
tk(idx) = tk(idx)-604800;
idx = tk<-302400;
tk(idx) = tk(idx)+604800;
end
##### 6 件のコメント4 件の古いコメントを表示4 件の古いコメントを非表示
Stephen23 2018 年 3 月 22 日

@gblmtc: I understand that there is a lot to learn, and it can seem quite daunting, but luckily MATLAB has easy-to-read documentation, which should always be the first place you look for information. You also might like to read this, it has some tips to keep in mind when learning MATLAB:
Stephen23 2018 年 3 月 22 日
Yes, you are right! Sometimes it is really really daunting. Sometimes I just say it is not for me and I just can't do it. Thanks for your help!

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

### カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

### Community Treasure Hunt

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

Start Hunting!

Translated by