Getting Error message 'Array indices must be positive integers or logical values.'

1 回表示 (過去 30 日間)
So, I have a question to do with leap Years. I have done all the code, just stuck with this error message. Here is my code
function [outputArg1] = GetLeapYears(startYear,endYear)
%UNTITLED12 Summary of this function goes here
% Detailed explanation goes here
m = (endYear - startYear)+1;
v = (startYear:1:endYear);
b = zeros(1,m);
for c = 1:m
b(c) = IsLeapYear(v(c));
end
outputArg1 = v(b);
and the IsLeapYear code is
function T = IsLeapYear(Year)
T = not (mod(Year, 4)) & (mod(Year, 100)) | not (mod(Year, 400));
end
  5 件のコメント
Stephen23
Stephen23 2021 年 1 月 24 日
編集済み: Stephen23 2021 年 1 月 24 日
"im just wondering why it works better?"
When you preallocate the array b as numeric and then later use indexing to allocate logical values to it, the array does not change class when you allocate (via indexing) those logical values, instead those logical values are coerced into numeric values. And then because a numeric array is not a logical array you cannot use it for logical indexing (only logical arrays can be used for logical indexing). Thus Kalyan Acharjya requires the extra comparison operator on the (coerced) numeric values to see if they are equivalent to true (coerced to numeric one) which creates a logical array which is basically a copy of that numeric array... so you just end up using twice as much memory with more operations.
Note that my simpler and more efficient answer did not involve any coercion or superfluous comparison or data duplication.
James Harrison
James Harrison 2021 年 1 月 24 日
It's a comment not an answer so im unable to accept it, however it has really helped me understand what im doing more. Thank you for your time and help!

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

採用された回答

KALYAN ACHARJYA
KALYAN ACHARJYA 2021 年 1 月 24 日
outputArg1 = v(b==1);
  3 件のコメント
Stephen23
Stephen23 2021 年 1 月 24 日
編集済み: Stephen23 2021 年 1 月 24 日
Note that this does not fix the problem at it source. See my comment for the simpler solution to your actual problem.
KALYAN ACHARJYA
KALYAN ACHARJYA 2021 年 1 月 24 日
編集済み: KALYAN ACHARJYA 2021 年 1 月 24 日
Thanks sir, Noted

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by