Clear Filters
Clear Filters

Multiply Individual Cells of a Matrix by a Scalar Using a For Loop

31 views (last 30 days)
I have a simple conversion problem where I have a matrix of pressure data (say p1) in hectopascals and need to convert the data to pascals by multiplying the individual elements by the scalar 100. While I understand this is as simple as multiplying the matrix variable by 100 (p1*100), I'm suppose to use a for loop to achieve this.

Accepted Answer

VBBV
VBBV on 15 Feb 2023
p1 = rand(100,1);% pressure matrix
for k = 1: length(p1)
P1(k) = p1(k)*100;
end
In this case, The previous solutions are certainly better compared to using a for loop however, if you are suppose to use a for loop then you can achieve it as above.
  2 Comments
Kenneth Louis
Kenneth Louis on 15 Feb 2023
I'm in the same class as the poster. Our instructor gave us a large matrix of data 96 x 144 cells and he wants us to use a for loop to convert the entire matrix into another matrix of the same demensions with all of the data multiplied by 100.
I am very sorry for the (potentially stupid) follow-up question, but how are we to get the output matrix to have the same demensions and have each individual cell multiplied by the scalar?
further, why doesn't the simple code
for x = p1
p1_output= x*100
end
work if p1 is the matrix in question? When I run this code, it only posts one column of output instead of all 144.

Sign in to comment.

More Answers (2)

Jai Khurana
Jai Khurana on 15 Feb 2023
You can use the .* operator to perform element-wise multiplication between a matrix and a scalar. For example, to multiply each element of matrix p1 by a scalar value 100, you can write:
100 .* p1
This will create a new matrix with the same dimensions as A, where each element of p1 is multiplied by 100.

Oguz Kaan Hancioglu
Oguz Kaan Hancioglu on 15 Feb 2023
You can elimnate for loop by using element wise multiplication in Matlab.
If you multiply the matrix with the scalar value * operator multiply all elements of the matrix using the same scalar.
pascal = 100*ones(5,5)
pascal = 5×5
100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100 100

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!