MATLAB: Vector indexes matrix columns indexingMATLAB Let M and N be natural numbers. Suppose X is an NxM matrix and y is an Nx1 vector. I want to do for i=1:N Z(i) = X(i, y(i));end without a for loop. How? Best Answer You can easily calculate the linear indices.X = [1,2,3,4;5,6,7,8;9,10,11,12];Y = [3;2;4];% Using linear indexing:A = X((1:size(X,1))+(Y.'-1)*size(X,1));% Your loop:for k = 1:numel(Y) Z(k) = X(k, Y(k));endAnd the outputs are identical:>> ZZ = 3 6 12>> AA = 3 6 12 Related SolutionsMATLAB: Newton Jacobi Nonlinear System Replacee(k+1)= max(xerr,yerr,zerr);withe(k+1)= max(max(xerr,yerr),zerr); MATLAB: Indexing into a n-by-m matrix using values from a n-by-1 matrix. Okay, I'm not totally clear and your for-loop does not do what your problem describes.We have an nxm matrix, x, for simplicity:x = magic(3);We have an nx1 vector y:y = [1;3;2];We want the columns of x to be indexed by y in to the rows of z:z = x(:,y)';This is what I understood from your description. Please clarify what is right or wrong with it.More per commentsx = magic(3);y = [1;3;2];z = x(sub2ind(size(x),(1:numel(y))',y)) Related QuestionCase instead of if-thenHow can i call array elements in a plot3 functionArray indices must be positive integers or logical values error , for the t(i) ,why3 equations 4 unknowns
Best Answer