Hello been trying to extract array from a big matrix so because of that taken magic(5) but issue is that when using for loop it works but trying to use in vectorization it gives error
2 次查看(过去 30 天)
显示 更早的评论
a=magic(5);
c=zeros(3,3,3);
for i=1:3
c(:,:,i)=a(i:3+(i-1),1:3)
end
above code works.
but issue is when using
i=1:3;
c(:,:,i)=a(i:3+(i-1),1:3)
it gives error
Assignment has fewer non-singleton rhs dimensions than non-singleton
subscripts
a(i:3+(i-1),1:3) is use to extract 3 x 3 matrix
0 个评论
回答(1 个)
Walter Roberson
2017-7-12
When you do
i=1:3;
a(i:3+(i-1),1:3)
then you are attempting to use a vector in the base position and a vector in the final position for the colon operator. Look again at https://www.mathworks.com/help/matlab/ref/colon.html#bviscw3-1 and see that those are required to be scalars.
MATLAB does not provide any direct way to do the kind of ragged indexing you want to do.
The approach you need to take in MATLAB is to use sub2ind() or equivalent to construct the linear indexes of the elements you wish to extract, and use linear indexing of the source array.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!