MATLAB Answers

Starting from the year 1697, store all leap years until 2017 in a vector. A leap year is a year which is divisible by 4 but NOT 100 but if the year is divisible by 100 then it must also be divisible by 400 to be considered a leap year.

1 ビュー (過去 30 日間)
Lakshan Bandara
Lakshan Bandara 2019 年 12 月 8 日
Edited: Stephen Cobeldick 2019 年 12 月 8 日
clc;
clear;
close all;
for x=1697:2017
if rem(x,4)==0 && rem(x,100)~=0
leap=x
end
if rem(x,100)==0 && rem(x,400)==0
leap=x;
end
end
This is how far I've gotten so far. Can someone please help me to finish the code ?

  0 件のコメント

サインイン to comment.

採用された回答

Stephen Cobeldick
Stephen Cobeldick 2019 年 12 月 8 日
編集済み: Stephen Cobeldick 2019 年 12 月 8 日
You made a good start, all you need is to use indexing or concatenation to store the values that you want to keep, e.g.:
lpy = [];
for x=1697:2017
if rem(x,4)==0 && rem(x,100)~=0
lpy(end+1) = x; % indexing into LPY
end
if rem(x,100)==0 && rem(x,400)==0
lpy(end+1) = x; % indexing into LPY
end
end
However this is not very neat, nor a very efficient use of MATLAB, because it expands lpy each time data is added to it. Much better would be to get rid of the loop entirely and use logical indexing, e.g.:
vec = 1697:2017;
idx = (rem(vec,4)==0 & rem(vec,100)~=0) | (rem(vec,100)==0 & rem(vec,400)==0);
lpy = vec(idx)

  0 件のコメント

サインイン to comment.

More Answers (0)

サインイン してこの質問に回答します。

タグ


Translated by