apply if-else-statement to a 3D matrix

3 views (last 30 days)
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

Accepted Answer

Dyuman Joshi
Dyuman Joshi on 26 Nov 2022
Edited: Dyuman Joshi on 26 Nov 2022
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 Comments
Dyuman Joshi
Dyuman Joshi on 26 Nov 2022
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.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!