Function that squares each elemnt of a matrix

조회 수: 98 (최근 30일)
Norty
Norty 2020년 3월 26일
답변: Harsh 2021년 10월 18일
Hi everyone,
I´m strugling with writing a function that is suppose to square each element of my matrix. I tried doing it through vector and then reshaping it, but couldn´t quite hit the correct code. My problem is that i figured out a part of the code but can´t really put it all together since im new to mathlab.
Having matrix n x m then
for 1:n
for 1:m
x.^2
end
end
but i dont really understand or know how to put in the function and what re the variables.
Thanks for any help.
  댓글 수: 2
Torsten
Torsten 2020년 3월 26일
You don't need the for-loops above.
If A is a matrix of arbitrary size, then A.^2 is the matrix with all entries squared.
Can you take it from here ?
Norty
Norty 2020년 3월 27일
I would. But I forgot to add, that its a excercise, where i have to write a loop function for squaring each element of matrix.

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

답변 (2개)

Peng Li
Peng Li 2020년 3월 26일
If you only want to square each element of a matrix, you use .^
For example:
A = randn(100, 100);
B = A.^2;
  댓글 수: 4
Peng Li
Peng Li 2020년 3월 27일
function A2 = myElementSquare(A)
A2 = nan(size(A)); % this pre-allocation speeds up the loop
for iR = 1:size(A, 1)
for iC = 1:size(A, 2)
A2(iR, iC) = A(iR, iC) .^ 2;
end
end
end
save above script as a function file. you can call this function by
Res = myElementSquare(anyNumericMatrix);
for example:
test = randn(100, 100);
test2 = myElementSquare(test);
Norty
Norty 2020년 3월 27일
works just perfectly, Thank you very much, now i understand what i needed!

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


Harsh
Harsh 2021년 10월 18일
a=[1 2; 3 4]
squa1=a^2
squa2=a.^2
squa1 =
7 10
15 22
squa2 =
1 4
9 16
so, for traditional square of the matrix use a^2
but, for square of each element use a.^2

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by