Displaying actual values from coded values for a for loop.

1 回表示 (過去 30 日間)
Wiktor Filo
Wiktor Filo 2021 年 1 月 5 日
コメント済み: Wiktor Filo 2021 年 1 月 5 日
function leap_year_list = get_leap_years(start_year, end_year)
A = [start_year : end_year];
for i = start_year : end_year
is_leap_year(i)
end
end
% I have a function is_leap_year with one input (year) which determines whether that year is a leap year or not. If it is it displays 'True', if not it displays 'False'. I am meant to use that function in another function get_leap_years to output a list of leap years from a range given by two inputs (start_year and end_year).
% I've created an array start_year : end_year and used a for loop with the is_leap_year function. It seems to work but instead of the actual list of years I get True/False.
eg. start_year = 2019, end_year = 2021
output:
'False'
'True'
'False'
When ideally my output should only read 2020, as 2020 is the only leap year for that given range. Any help on how to tackle this is appreciated. Many thanks.

採用された回答

Mischa Kim
Mischa Kim 2021 年 1 月 5 日
編集済み: Mischa Kim 2021 年 1 月 5 日
Wiktor, simply replace the is_leap_year(i) command with an if statement. Quick and dirty:
if (strcmp(is_leap_year(i),'True'))
display(A(i))
end
Better yet, make the return value of is_leap_year(i) a logical value (vs string). And replace the loop index i by ii, as i is also the imaginary unit in MATLAB. This would chnage your code to:
if is_leap_year(ii)
display(A(ii))
end
  1 件のコメント
Wiktor Filo
Wiktor Filo 2021 年 1 月 5 日
Thank you so much this works perfectly!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeData Types についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by