MATLAB Answers

How to square each element of a vector

5,492 views (last 30 days)
Daniel
Daniel on 31 Jan 2012
Answered: Saurabh Palve on 23 Jan 2020
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!

  1 Comment

Sign in to comment.

Accepted Answer

Dr. Seis
Dr. Seis on 31 Jan 2012
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

  0 Comments

Sign in to comment.

More Answers (4)

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

  0 Comments

Sign in to comment.


Jabir Mumtaz
Jabir Mumtaz on 30 May 2018
y=x.^2;

  0 Comments

Sign in to comment.


Al Mamun
Al Mamun on 21 Jan 2020 at 13:06
how to get B=[A A+32;A+48 A+16] and what is the size of B
give me the solution

  0 Comments

Sign in to comment.


Saurabh Palve
Saurabh Palve on 23 Jan 2020 at 5:41
x=[2 5 1 6]^2

  0 Comments

Sign in to comment.

Sign in to answer this question.