How can I fix "Index in position 2 exceeds array bounds" in for loop ?

7 visualizzazioni (ultimi 30 giorni)
Rajeev Kumar il 7 Nov 2022
Modificato: Joan il 8 Nov 2022
Code:
A= datafile
sumArray = [];
for c = 1:length(A)
col = A(:,c);
sum1 = rms(A(:,c));
sumArray = [sumArray,sum1];
end
s=sumArray'
Attached file = A
Error : Index in position 2 exceeds array bounds (must not exceed 11).
0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

Risposta accettata

CHIRANJIT DAS il 7 Nov 2022
@Rajeev Kumar You are giving dimension of row in the for loop. Perhaps you can replace length(A) with size(A,2). Revised code looks like the below one..
sumArray = [];
for c = 1:size(A,2)
col = A(:,c);
sum1 = rms(A(:,c));
sumArray = [sumArray,sum1];
end
s=sumArray'
Cheers
1 CommentoMostra -1 commenti meno recentiNascondi -1 commenti meno recenti
Rajeev Kumar il 7 Nov 2022
This code works, thanks

Accedi per commentare.

Più risposte (2)

Askic V il 7 Nov 2022
Modificato: Askic V il 7 Nov 2022
This is because you're not using length correctly. In fact it is not a good idea to use length when working with matrices.
% A is a matrix with dimensions: 1024x11
[nrRows, nrCols] = size(A)
ll = length(A)
I hope you understand now. You have only 11 columns in a matrix, but you're trying to iterate loop from 1 to 1024, where in fact 1024 is the number of rows.
0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

Joan il 7 Nov 2022
Modificato: Joan il 8 Nov 2022
W=cell(p,1);
for j=1:(p-1);
w=A(index(j):index(j+1)-2);
W{j}=w;
W2=cell(p,1);
for j=1:(p-1);
w2=A(index(j):index(j+1)-2);
W2{j}=w2
end
Z=
cell
(p,1);
for ii=1:p
P1=W{ii,1};
Z{ii,1}=P1(3:3:end);
end
for ii=1:p
P2=Z{ii,1};
if P2(end,1)>0
W2(ii,1)={[]};
end
end
0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

Categorie

Scopri di più su Matrix Indexing in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by