필터 지우기
필터 지우기

How to extract elements from each dimension of a 3D matrix and put it in a vector.

조회 수: 2 (최근 30일)
I have a 3D matrix that is
B = (31, 37, 91);
I would like to extract all the elements from each dimension, and place it in a vector, then take the variance of the vector.
In the end, I would like to make a vector of all of the variances.
For example,
C = [Var1; Var2; ... Var91];
Below is what I have tried so far, but I am curious if there is a way without doing each dimension individually.
Thanks in advance!
F1 = B(:,:,1);
F1v = F1(:); %vector
Var1 = var(F1v);
F2 = B(:,:,2);
F2v = F2(:); %vector
Var2 = var(F2v);

채택된 답변

Guillaume
Guillaume 2019년 9월 9일
Sure, you just have to type the same code 91 times...
As you can guess, that's not a viable approach. If you start numbering variables, you're doing it wrong.
If you're on R2018b or later, it's trivial to obtain your vector:
V = var(B, 0, [1 2]); %requires R2018b or later
Optionally, you can squeeze the result, but having a vector along the page makes more sense.
In earlier versions, var can only operate on one dimension at once, so you must first reshape your matrix into an Nx91 matrix:
V = var(reshape(B, [], size(B, 3)))
  댓글 수: 1
Anna M
Anna M 2019년 9월 9일
편집: Anna M 2019년 9월 9일
Thanks! The reason I am numbering my variables is because I use the individual vectors of each dimension in other calculations. However, I am a beginner, so I am working on consicing my code and becoming less redundant..
Your suggestion gave me exactly what I needed. I do have a question, what does the [1 2] mean in: V = var(B, 0, [1 2]);
I did not want to use that if I did not fully understand.
Edit*: I see it now! I read it means for dimensions 1 and 2. Thanks again

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix and Vector Construction에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by