필터 지우기
필터 지우기

How to square each element of a vector

조회 수: 329 (최근 30일)
Daniel
Daniel 2012년 1월 31일
편집: John D'Errico 2023년 3월 12일
Hello everybody I have a very simple problem, but I don't know how to solve it.
I want to create a row vector from a certain range between two limits. So, given the limits 'a' and 'b', I do: x = [a:0.1:b] %I obtain a vector with equally spaced values between 'a' and 'b', with a 0.10 step.
The problem is that now, I need to elevate each value of 'x' to square, and so, obtain a new vector, let's say 'y', that will contain the values of 'x' squared. How do I do this???
Example: x = [0:1:4] ans = 0 1 2 3 4
I need y to be: 0 1 4 9 16
Thanks everyone!

채택된 답변

Dr. Seis
Dr. Seis 2012년 1월 31일
y = x.^2;
Using the "." will effectively perform element-by-element mathematical operations. So if you had 2 MxM matrices, say A and B, then:
C = A*B;
Would yield normal matrix multiplication, while:
C = A.*B;
Would yield element-by-element multiplication of both matrices.
See example below:
>> A = eye(2)
A =
1 0
0 1
>> B = rand(2)
B =
0.9594 0.1745
0.9917 0.9862
>> A*B
ans =
0.9594 0.1745
0.9917 0.9862
>> A.*B
ans =
0.9594 0
0 0.9862

추가 답변 (4개)

the cyclist
the cyclist 2012년 1월 31일
y = x.^2;
If you don't need the intermediate variable x, then you could simply have done
y = (a:0.1:b).^2;

Jabir Mumtaz
Jabir Mumtaz 2018년 5월 30일
y=x.^2;

Saurabh Palve
Saurabh Palve 2020년 1월 23일
x=[2 5 1 6]^2
  댓글 수: 2
Kyle Delaney
Kyle Delaney 2020년 12월 20일
You forgot the dot
John D'Errico
John D'Errico 2023년 3월 12일
편집: John D'Errico 2023년 3월 12일
For any newbies who might see this question, of the many answers I see here, all the others are correct, but this answer by @Saurabh Palve is not correct in MATLAB. Without a dot in that operator, that line will fail.

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


MUHAMMAD FAIZAN ALI
MUHAMMAD FAIZAN ALI 2023년 3월 12일
>> A=[4 3;1 2]
A =
4 3
1 2
>> A.^2
ans =
16 9
1 4

카테고리

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