Effacer les filtres
Effacer les filtres

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

44 vues (au cours des 30 derniers jours)
Jordan David
Jordan David le 15 Fév 2023
Commenté : Jordan David le 23 Fév 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.

Réponse acceptée

VBBV
VBBV le 15 Fév 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 commentaires
Kenneth Louis
Kenneth Louis le 15 Fév 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.
Jordan David
Jordan David le 23 Fév 2023
Thank you!

Connectez-vous pour commenter.

Plus de réponses (2)

Jai Khurana
Jai Khurana le 15 Fév 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 le 15 Fév 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

Catégories

En savoir plus sur Data Type Conversion dans Help Center et File Exchange

Tags

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by