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 views (last 30 days)
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

Answers (1)

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

Sign in to comment.

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!