Help with matrix indexing.

1 回表示 (過去 30 日間)
Lucy
Lucy 2011 年 1 月 26 日
C is a matrix with i rows and 5 columns. i=1:16
I am interested in finding the value of C(i-1,:).
Using the following matlab code, I try to direct matrix c row i-1 any column to c row 16 any column when i equals 1.
if i==1
c(i-1,:)=c(16,:);
end
Error: Subscript indices must either be real positive integers or logicals.
Problem: It gives me above error message as it seems always recognize the c(i-1,:)=c(0,:) first and therefore ignore the statement after that which is equalling to the c(16,:).
Any idea how to solve it?

採用された回答

the cyclist
the cyclist 2011 年 1 月 26 日
You seem to be treating this in a sorta symbolic way trying to tell MATLAB that the c(i-1) element is really element c(16,0) when i==1. However, what you have done in practice is an assignment statement,
>> c(0,:) = c(16,:)
which is not valid because you can't assign to element c(0,:).
I think the easiest way to accomplish what you want is to use the CIRCSHIFT command:
>> index = (1:16)'
>> down_one_index = circshift(index,1)
The guts of CIRCSHIFT, in your case, is the following use of MOD:
>> mod((0:15)-1, 16)+1
This creates the periodic indexing that you want. Hope that helps.
the cyclist

その他の回答 (3 件)

Siddharth Shankar
Siddharth Shankar 2011 年 1 月 26 日
if "i" is 1, then you can not index into c with the row index "i-1". MATLAB uses 1-based indexing. You need to "special case" your code to avoid indexing into row 0, or a row value that is negative, as the error message suggests.

Lucy
Lucy 2011 年 1 月 26 日
Hi, I solved the problem by using
if i==1
cellindex=16;
elseif i~=1
cellindex=i-1;
c(cellindex,:)
end
Thank you both anyway.
  2 件のコメント
the cyclist
the cyclist 2011 年 1 月 26 日
Glad you found a solution. Be aware that applying logic functions to handle special cases is in general going to be slower than vectorized solutions like the one I proposed.
Lucy
Lucy 2011 年 1 月 26 日
I can see your point now. Thanks

サインインしてコメントする。


Paulo Silva
Paulo Silva 2011 年 1 月 26 日
Lucy there's no need for any if statements or other fancy functions
nrows=16 %choose the number of rows (horizontal lines)
indrow=2:nrows+1 %create the index of the rows, the trick is here (+1)
C(indrow-1,:) %no problem now, indrow-1 is never zero
  2 件のコメント
the cyclist
the cyclist 2011 年 1 月 26 日
Lucy's trying tell MATLAB that the row "below" row 1 should be row 16. (Periodic boundary condition.) I don't see how your indexing does this. "indrow-1" seems to just be 1:16. Do I misunderstand?
Paulo Silva
Paulo Silva 2011 年 1 月 26 日
Now I understand, thanks for the good explanation :) forget about my code, it just rotates the rows 180º

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMultidimensional Arrays についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by