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

68 次查看(过去 30 天)
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.

采纳的回答

VBBV
VBBV 2023-2-15
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 个评论
Kenneth Louis
Kenneth Louis 2023-2-15
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.

请先登录,再进行评论。

更多回答(2 个)

Jai Khurana
Jai Khurana 2023-2-15
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
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

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by