apply if-else-statement to a 3D matrix

조회 수: 3 (최근 30일)
Angelavtc
Angelavtc 2022년 11월 26일
댓글: Angelavtc 2022년 11월 26일
Dear community,
Maybe this is a somewhat obvious question, but I have a 3D matrix with normally distributed simulations like the following:
n=10000
x1 = 75:125;
y1 = 0:40;
Qd=zeros(n,length(y1),length(x1));
for i = 1:length(x1) % mean
for j = 1:length(y1) % sd
Qd(:,i,j)=normrnd(x1(i),y1(j),n,1);
end
end
Based on this matrix, I want to create another one with 3 conditionals. If the element Qd(k,i,j) is less than 25 then the new matrix should have a 50; if it is between 25 and 50 it should give me 10; if it is greater than 50 it should give me 30. The problem is that I have tried with the following and the elseif command is not working properly :( Any hint will be really appreciated! Thank you!
Pw=zeros(n,length(y1),length(x1));
for k = 1:n
for i = 1:length(x1)
for j = 1:length(y1)
if Q_d(k,i,j)<=25
Pw(k,i,j)=50;
elseif 25<Q_d(k,i,j)<=50
Pw(k,i,j)=10;
else
Pw(k,i,j)=30;
end
end
end
end

채택된 답변

Dyuman Joshi
Dyuman Joshi 2022년 11월 26일
편집: Dyuman Joshi 2022년 11월 26일
The syntax for comparing multiple conditions is individualistic in MATLAB, i.e. you have to write code for each condition individually -
elseif 25<Q_d(k,i,j) && Q_d(k,i,j)<=50
Edit - The pre-allocation of Pw w.r.t to the individual dimensions and the loop indices does not match
  댓글 수: 3
Dyuman Joshi
Dyuman Joshi 2022년 11월 26일
Pw=zeros(n,length(y1),length(x1));
You initialised Pw with dimensions corresponding to n, y1 and x1 respectively. However, in your loop
for k = 1:n
for i = 1:length(x1)
for j = 1:length(y1)
if Q_d(k,i,j)<=25
The respective loop variables correspond to n, x1 and y1. Which are not equal to n, y1 and x1 (order) as in the definition of Pw.
%Either you can change the order of indices
Q_d(k,j,i)
%or change the loop parameters.
I hope you get my point.
Angelavtc
Angelavtc 2022년 11월 26일
Sure! thank you @Dyuman Joshi :)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by