필터 지우기
필터 지우기

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

조회 수: 31 (최근 30일)
Jordan David
Jordan David 2023년 2월 15일
댓글: Jordan David 2023년 2월 23일
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
Oguz Kaan Hancioglu 2023년 2월 15일
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에서 Data Type Conversion에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by