Index exceeds the number of array elements: in case of for loop.

I have this code where simple permutation will be performed , but i am getting an error message as "Index exceeds the number of array elements (8)."
k4='00000000000000000000000000000000';
k4=reshape(k4,8,[]);
k4=bin2dec(k4);
Perm=[0 4 8 12 16 20 24 28 32 36 40 44 48 52 56 60 ...
1 5 9 13 17 21 25 29 33 37 41 45 49 53 57 61 ...
2 6 10 14 18 22 26 30 34 38 42 46 50 54 58 62 ...
3 7 11 15 19 23 27 31 35 39 43 47 51 55 59 63];
for i = 1:8
j4(i)=k4(Perm(i)+1);
end

3 件のコメント

David Hill
David Hill 2020 年 12 月 9 日
You just need to look at k4 after line 3 to see it only has 8 elements. You are trying to index way beyond 8.
%when i=3, your loop will fail
j4(3)=k4(Perm(3)+1)=k4(9);%k4(9) does not exist!
Maria Imdad
Maria Imdad 2020 年 12 月 9 日
how should i update my loop, so that it permutes all of the 8 values in k4?
David Hill
David Hill 2020 年 12 月 9 日
k4 is all zeros. What do you mean by permuting all 8 values? Provide an example.

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

回答 (1 件)

Timo Dietz
Timo Dietz 2020 年 12 月 9 日
編集済み: Timo Dietz 2020 年 12 月 9 日

1 投票

k4 has 8 members.
But the third member of Perm is 8. So plus one leads to 9 which is more than k4 contains k4(Perm(i)+1) = k4(9);
To me it's not clear what you try to do. Could you please give an example of the expected result?
Btw., are you aware of the built-in "permute" function?

3 件のコメント

Maria Imdad
Maria Imdad 2020 年 12 月 9 日
i want to use this matrix perm to permute my string k4. because value of k4 will chnage in every loop. so whatever is in the k4 i want it to be permuted.
Daniel Pollard
Daniel Pollard 2020 年 12 月 9 日
What do you mean by permute in this context?
Timo Dietz
Timo Dietz 2020 年 12 月 9 日
編集済み: Timo Dietz 2020 年 12 月 9 日
If you just want to rearrange k4, as I wrote, "permute" is the function you need.
But certainly you can't use a higher index in your Perm array than present in k4.

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

カテゴリ

ヘルプ センター および File ExchangeMatrix Indexing についてさらに検索

質問済み:

2020 年 12 月 9 日

コメント済み:

2020 年 12 月 9 日

Community Treasure Hunt

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

Start Hunting!

Translated by