"Index exceeds matrix dimensions."

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

 采纳的回答

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

更多回答(1 个)

This code runs to completion
A = rand(10,6);
columnsA=length(A); % number of columns in my dataset A
disp(columnsA);
waves=1; %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
The difference from what you posted is that I added some made-up data at the beginning, and I set the values of "waves" to 1, since I don't know what "i" is.
You'll need to specify the problem better, for example by posting your real data and value of i.

3 个评论

If you'd made your matrix |A| taller (e.g. 16 rows) , you'd have hit the same problem due to the use of |length|.
My code still runs to completion if I swap in
A = rand(16,10);
So, I'm still unclear on am514's problem.
The number of rows needs to be over least twice the number of columns for the code to fail, since then columnsA/2 (actually half the number of rows) is greater than the actual number of columns.

请先登录,再进行评论。

类别

在 帮助中心 和 File Exchange 中查找有关 Matrix Indexing 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by