Loop: Index Exceeds Matrix Dimensions / less values than required.

1 view (last 30 days)
Hello Everyone,
How can settle the following code so that It may run properly.
clear;
clc;
load('Dataset.mat'); % length of dataset is 189.
start_limit = 1; % initialization
end_limit = 6; % initialization
Final = struct(); % structure
limit = (length(Dataset))/6; % I want to have a division of 6. i.e. 189/6 = 31.5
for i = 1:limit % Note: Length of Dataset is 189
Values = Dataset(start_limit:end_limit,13); % runs best till 186, since 186 is wholy divisble by 6.
FieldName = strcat('Name', num2str(i));
Final.(FieldName) = cell2mat(Values);
start_limit = start_limit+6;
end_limit = end_limit+6;
end
Code runs till 186 but i want to have a values till 189. When i add +1 to limit, i got following error:
Index exceeds matrix dimensions.
Error in Untitled (line 35)
Values = Dataset(start_limit:end_limit,13);
I understand the error but how to overcome this?
Any help would be appreciated :-)
Regards,
Waqar Ali Memon

Accepted Answer

Rik
Rik on 23 Jul 2019
If it is fine to use fewer values for the end of your loop, you can do this:
%replace this
Dataset(start_limit:end_limit,13)
%by this
Dataset(start_limit:min(end_limit,end),13)
However, you should probably not be using a struct with numbered fields. I would suggest a struct array instead.
  1 Comment
Waqar Ali Memon
Waqar Ali Memon on 23 Jul 2019
Thank you Rik, for elegant and accurate solution. :-). I would be getting in your suggestion as well :-).

Sign in to comment.

More Answers (0)

Products


Release

R2017b

Community Treasure Hunt

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

Start Hunting!