Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

How to discover where code ends.

조회 수: 2 (최근 30일)
DJ V
DJ V 2016년 11월 27일
마감: MATLAB Answer Bot 2021년 8월 20일
function  days  = day_diff( M1,D1,M2, D2 )
%DAY_DIFF Summary of this function goes here
%   Detailed explanation goes here
if M1 ~= 1 && M1 ~= 2 && M1 ~=3 && M1 ~= 4 && M1 ~= 5 && M1~=6 && M1~=7 && M1~=8 && M1~=9 && M1~=10 && M1~=11 && M1 ~= 12
days = -1;
return;
end
if M2 ~= 1 && M2 ~= 2 && M2 ~=3 && M2 ~= 4 && M2 ~= 5 && M2~=6 && M2~=7 && M2~=8 && M2~=9 && M2~=10 && M2~=11 && M2 ~= 12
days = -1;
return;
end
if D1 > 31 || D1 < 1
days = -1;
return;
end
if D2>31 || D2<1
    days = -1
    return;
end
if M1 ==1 || M1 ==2 || M1 ==3 || M1 ==4
 if D1 <1 || D1 >30
 days = -1;
 return;
end
end
if M2 ==1 || M2 ==2 ||M2 ==3 || M2 ==4
 if D2 <1 || D2 >30
 days = -1;
 return;
end
end
total =0;
if M2<M1
    for count=M2+1:M1-1
        if M1==4 ||M1==6||M1==9||M1==11
            add = 30;
        else
            add = 31;
        end
        total = total + add;
    end
end
if M2<M1
    if M2 == 4 || M2 == 9 || M2 == 11 || M2==6
        diff = 30-D2;
    else
        diff = 31-D2;
    end
end
if M1<M2
    if M1 == 4 || M1 == 9 || M1 == 11 || M1==6
       diff = 30-D1;
    else
        diff = 31-D1;
    end
end
total =0;
if M2>M1
    for count=M1+1:M2-1
    if count == 4 || count == 9 || count == 11 || count==6
        days2 = 30;
    else
        days2 = 31;
    end
    total = total + days2;
    end
end        
if M1>M2
    for count=M2+1:M1-1
    if count == 4 || count == 9 || count== 11 ||count==6
        days2 = 30;
    else
        days2 = 31;
    end
    total = total+days2;
end    
if M1 > M2
    days = total + diff + D1;
else
    days = total + diff + D2;
end
end

How do I discover where Matlab believes this code ends? Its telling me I assign no value to "days" in the code, but I do at the end.

  댓글 수: 1
Stephen23
Stephen23 2016년 11월 27일
편집: Stephen23 2016년 11월 27일
This code is a good example of why badly formatted code causes so many problems. When the code is indented properly, then some problems become much clearer. Open the code in the MATLAB editor, select all of the code, and then click ctrl+i. This will align and indent the code using MATLAB's normal rules. It will also make it clear that your if's and end's in the last two if blocks are not matching as you think they are. Using consistent formatting will make finding the problem easier.
Those using octave can use this online tool: http://base-n.de/matlab/code_beautifier.html

답변 (1개)

David Goodmanson
David Goodmanson 2016년 11월 27일
Hello DJ, Looks like your very last 'end' statement needs to be moved up about half a dozen lines so it goes with the second-to-last 'if M1>M2' block. Right now if M1<=M2, the last 'if M1>M2' block never happens.

이 질문은 마감되었습니다.

Community Treasure Hunt

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

Start Hunting!

Translated by