MATLAB: “Index exceeds matrix dimensions.”

exceedsindex

Hi, can somebody figure out why I get this error message? Thank you very much!
columnsA=length(A); % number of columns in my dataset A
disp(columnsA);
waves=i; %i is a number I found by iteration before but for next should be
%fixed
j=2; % iteration variable
k=1; % iteration variable
B=ones (1,(columnsA/2)); %new vector where I want to store the iterated
%values
while (j<= (columnsA/2) && k < ((columnsA/2)-1)) %iteratio over columns
%in dataset in specific row waves
x = A(waves,j); %x is values I want to store in new vector from
%dataset A at location waves, j
B(1,k)=x; % store the new value in B
j=j+2; % increse j by 2 (only want to store every other value from
%that row
k=k+1; % increase iterator for vector B
end

Best Answer

columnsA=length(A); % number of columns in my dataset A
No it isn't, columnsA may be the number of columns or the number of rows, whichever is the greatest.
I would recommend never using length. Use numel if using a vector (or using linear indexing on a 2d matrix) and use size with an explicit dimension on a matrix:
columnsA = size(A, 2); %number of columns in my dataset A