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

回答(1 个)

Walter Roberson
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.
  6 个评论
ARSALAN RIAZ
ARSALAN RIAZ 2017-7-15
well thanks. is therte any way to Multiplying each matrix column by a column vector without using bsxfun? purpose is to make code faster

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by