How to write this matlab code?
이전 댓글 표시
Hi
I have the below equation and I want to solve by matlab, but i am little bit confused how to write.
A=(B-mean(B))*P
C=A^2
B is matrix of 8760X30 and P is vector of 30X1.
do i need to use for loop to solve it or how will you write it??
Thanks in advance
채택된 답변
추가 답변 (2개)
ME
2020년 3월 9일
Assuming you want the mean of the whole matrix (not mean by row/column or something else) then the first line will be:
A = (B - mean(B(:)))*P;
which will give an 8760x1 array. You can then do your second line as:
C = A.^2;
assuming you want each element squared - which I guess must be what you want because otherwise the dimensions don't work out.
댓글 수: 1
Benjamin Großmann
2020년 3월 9일
Since R2018b there is an option for that
mean(B, 'all')
This is also available for min() and max() (and maybe for others).
Benjamin Großmann
2020년 3월 9일
In Matlab, you could write something like
B = rand(8760, 30); % matrix B of size 8760x30 with random values
P = rand(30, 1); % vector P of size 30,1 with random values
A =(B-mean(B))*P;
BUT: Matlab computes the mean of each column of B resulting in a row vector. Then this row vector is substracted from the matrix B, where we do have a problem from a mathematical perspective. Here, matlab replicates the row vector "mean(B)" 8760 times to fit the dimensions of B.
You could also pass the option 'all' to the mean function to get the mean of all matrix elements, then the result is a scalar and the dimensionaity does fit.
Either way, your output from the first equation A is a column vector 8760x1. This being said, the second equation also gives a problem from a mathematical perspective. To square all elements of this vector you could use the dot operator C=A.^2 or, if you intend to calculate the scalar product, you can write C=A'*A; which transposes the vector before multiplication with itself.
댓글 수: 2
John D'Errico
2020년 3월 9일
Be careful with recommending A'*A. If the elements of A are real numbers, then the result is simply the sum of squares. However, if the elements of A might be cpomplex, then it is NOT just the sum of squares of elements. the ' operator is a CONJUGATE transpose.
Benjamin Großmann
2020년 3월 9일
Yes, thanks for the advice. A.'*A is for the non-conjugate transpose
카테고리
도움말 센터 및 File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!