Multiply Individual Cells of a Matrix by a Scalar Using a For Loop
74 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Jordan David
el 15 de Feb. de 2023
Comentada: Jordan David
el 23 de Feb. de 2023
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.
0 comentarios
Respuesta aceptada
VBBV
el 15 de Feb. de 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 comentarios
Kenneth Louis
el 15 de Feb. de 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.
Más respuestas (2)
Jai Khurana
el 15 de Feb. de 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.
0 comentarios
Oguz Kaan Hancioglu
el 15 de Feb. de 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)
0 comentarios
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!