matrix and vector indices out of range

조회 수: 3 (최근 30일)
Leor Greenberger
Leor Greenberger 2011년 9월 20일
Hi guys,
I have the following code:
K = 20*10^3;
X = zeros(1,K/2+1);
w = 10
wi = repmat(1:w,length(i),1);
wi =
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
Xind = [751 1500 2250 2999 3749]; %this was actually calculated.
ind_plus_wi = bsxfun(@plus,wi,Xind');
ind_plus_wi =
Columns 1 through 10
752 753 754 755 756 757 758 759 760 761
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510
2251 2252 2253 2254 2255 2256 2257 2258 2259 2260
3000 3001 3002 3003 3004 3005 3006 3007 3008 3009
3750 3751 3752 3753 3754 3755 3756 3757 3758 3759
i = 1:5;
i_M = repmat(i',1,w);
i_M =
1 1 1 1 1 1 1 1 1 1
2 2 2 2 2 2 2 2 2 2
3 3 3 3 3 3 3 3 3 3
4 4 4 4 4 4 4 4 4 4
5 5 5 5 5 5 5 5 5 5
v = 1:5;
X(ind_plus_wi) = v(i_M);
Here, I defined X to have indices from 1:K/2+1 and I am using the values of ind_plus_wi to set values in X as such: X(ind_plus_wi) = v(i_M). But it is possible under certain circumstance for ind_plus_wi to have values that are outside the interval of X(1:K/2+1). I would like to skip over those. In the case where ind_plus_wi > K/2+1, I could just do X = X(1:K/2+1) and discard that data. However, if ind_plus_wi < 1, MATLAB will produce an error that I can't recover from. What can I do? Thanks!

채택된 답변

Leor Greenberger
Leor Greenberger 2011년 9월 20일
Thinking about it, I could probably do:
ind_plus_wi(ind_plus_wi < 1) = K/2+2
and
X(ind_plus_wi) = v(i_M);
X = X(1:K/2+1);

추가 답변 (1개)

Fangjun Jiang
Fangjun Jiang 2011년 9월 20일
The problem is about the variable i.
Many people use i as a variable to do iteration in a for-loop, for example i=1:5.
Without knowing that i actually is a built-in constant. Do this:
clear all
length(i)
help i
In your code, you used length(i) first without assign value to i. So it is thinking that you are use i as the Imaginary unit. That is why it gives error.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by