Using if-statements seperatly for each value in an array

I use if-statements which depend on a certain value. Now, instead of this single value, I have an array with a number of values (roughly 500), each representing one machine. Now for each of these values, the if statement should make a decision. I could do this with a loop around the if-statement, running the loop once for each value. However, all of this is iterated for 60.000 time steps or more, so this kind of loop slows down the simulation immensely. Do you see any smarter way of doing what I put in the example code? Basically a way in which in one go, all the if-statement is applied individually to each array value?
numberOfMachines = 500;
x = randi([0,1],numberOfMachines,1);
for n=1:numberOfMachines
if x(n) == 1
y(n) = 10;
else
y(n) = 0;
end
end

 채택된 답변

David Hill
David Hill 2022년 2월 9일
numberOfMachines = 500;
x = randi([0,1],numberOfMachines,1);
y=zeros(size(x));
y(x==1)=10;

댓글 수: 4

or
numberOfMachines = 500;
y = 10*(randi(2,numberOfMachines,1)-1);
or
numberOfMachines = 500;
x = randi([0,1],numberOfMachines,1);
y=x*10;
since filled x with 0,1.
The latter above doesn't pair y with x unless reset the seed; as written it will generate a new random sample. This, of course, presumes, OP wants/needs both x and y; if only y is the needed end result then generating directly is most efficient, true.
Thank you for your answer! Is it possible to combine multiple conditions this way, something like y(x==1,z>3)=10; ?
and can I put or conditions? How would you go about the following example?
S_FS = randi([0,1],numberOfMachines,1);
S_SR = randi([0,1],numberOfMachines,1);
A = randi([0,10],numberOfMachines,1);
B = randi([0,10],numberOfMachines,1);
A_deact = 5;
B_deact = 5;
if S_FS == 1
if A > A_deact || B < B_deact
S_FS = 0;
S_SR = 1;
end
elseif S_FS == 0 && S_SR == 0
S_FS = 1;
end
Never mind, sorry for stupid questions, found the answer here: https://de.mathworks.com/help/matlab/learn_matlab/workspace.html
Thanks again!

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Data Distribution Plots에 대해 자세히 알아보기

제품

릴리스

R2021a

태그

Community Treasure Hunt

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

Start Hunting!

Translated by