How to store matrix values in a vector?

11 次查看(过去 30 天)
Hello everyone,
I have a 10x10x10 matrix of which I want extract element (10,4,10),(9,4,9),(8,4,8) and so on... then element (10,5,10),(9,5,9),(8,5,8) and so on... then store these values as consecutive entries in vectors, and then create a matrix out of the vectors, like so:
m = rand(10,10);
vec(1)_1 = m(10,4,10) % first vector, first element
vec(2)_1 = m(9,4,9) % first vector, second element
...
vec(1)_2 = m(10,5,10) % second vector, first element
vec(2)_2 = m(9,5,9) % second vector, first element
...
mat(i,:) = vec_1, vec_2, vec_3, etc. % matrix containing vectors as columns
My take on it so far is the following:
m = rand(10,10);
for i = 1:10
for k = 10:-1:1
vec(i) = m(k,4:7,k)
mat(i,:) = vec_1, vec_2, vec_3, etc.
end
end
I know the problem is that I'm looping over all then numbers in k before jumping to the next i, which means only the last k will get stored in vec(i) each time. Also I don't really know how to differentiate between the elements of vec(i) and the whole vector itself vec_i. Any help is really appreciated. Thank you.

采纳的回答

Mark Whirdy
Mark Whirdy 2012-12-4
编辑:Mark Whirdy 2012-12-4
Hi Peter
Finding it a little difficult to totally grasp what you want to do e.g. m is a 3d matrix & not a 2d one, right?
My take is that you want to access the 3d-diagonals [e.g. (10,4,10),(9,4,9),(8,4,8) ] of a matrix
The code below will do this - the columns of "m" below being the required 3d-diag vectors of "M", which can then be flipped if the order is not what you required.
M = rand(10,10,10); our starting 3d matrix
M_p = permute(M,[1 3 2]); % 3-d rotation
A = eye(10); A = repmat(A,[1,1,10]); % 3d identity for logical indexing
m = M_p(A==1); % extract the 3d-diagonal elements of the M_p rotation
m = reshape(m,10,10); % convert single vector to matrix whose columns are the required "3d diagonal-vectors"
If it is necessary that the vectors begin at 10 (i.e. i=10:-1:1 & k=10;-1:1) then use flipud and fliplr as appropriate
m = fliplr(flipud(m));
Is this what you were looking for?
Best Rgds,
Mark
  1 个评论
Peter
Peter 2012-12-6
Mark,
thank you for your help. This was exactly what I was trying to do. Your approach is so much better and useful for me. Thanks a lot.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by