Create a matrix of average Values from a Vector

조회 수: 1 (최근 30일)
Johanna Popp
Johanna Popp 2022년 1월 2일
편집: Image Analyst 2022년 1월 2일
Hi all,
It would be great if you could help me solve this problem!
I have a vector of 5 numbers [2 4 8 9 12] and want to create a matrix with the size 5*5 containing the average of each of the respective pairs of numbers in the corresponding field of the matrix. In this case it would be
[2 3 5 5.5 7;
3 4 6 6.5 8;
5 6 8 8.5 10;
5.5 6.5 8.5 9 10.5;
7 8 10 10.5]
How could I implement this with code? Would this be the right implementation?
vector = [2 4 8 9 12];
for i = 1:5
for j = 1:5
matrix(i,j) = (vector(i) + vector(j))/2;
end
end
matrix
matrix = 5×5
2.0000 3.0000 5.0000 5.5000 7.0000 3.0000 4.0000 6.0000 6.5000 8.0000 5.0000 6.0000 8.0000 8.5000 10.0000 5.5000 6.5000 8.5000 9.0000 10.5000 7.0000 8.0000 10.0000 10.5000 12.0000
Thanks!
Johanna
  댓글 수: 1
Torsten
Torsten 2022년 1월 2일
편집: Torsten 2022년 1월 2일
Yes.
Or simply
matrix = 0.5*(vector+vector.')

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

답변 (1개)

KSSV
KSSV 2022년 1월 2일
The same implementation without loop:
matrix = (vector+vector')/2 ;
When you have used a loop, you need to initilaizethe matrix into zeros.
matrix = zeros(5) ;

카테고리

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