how to store the conditional loop data

sir/ madam please correct me.
ut=rand(15,1);
uy=([0.84;0.384;0.784]);
eval (['U_y','=[u_y;u_y;u_y;u_y;u_y]']);
for n=1:15
if ut(n,1)<=U_y(n,1)
ut(n,1)=ut(n,1);
else
ut(n,1)=0;
end
utt(:,1)=ut(n,1); %% i want to store the ut as a utt in a column
end

4 Comments

Avoid cluttering unneeded parentheses:
uy=([0.84;0.384;0.784]);
% ^ ^ not useful
Do not use eval() in general, most of all if it can be replaced directly:
% eval (['U_y','=[u_y;u_y;u_y;u_y;u_y]']); Nope
U_y = [u_y; u_y; u_y; u_y; u_y];
% Or more clearly:
U_y = repmat(uy, 5, 1);
It is not useful to write code, which does not do anything:
ut(n,1)=ut(n,1); % ??? Why?
ut(n,1)=ut(n,1)
because i want that specific element of ut which satisfy the condition and rest is zero after that i want to store it as utt.
My code tests each element of ‘ut’ against ‘U_y’ and sets it to zero if the condition is satisfied.
What result do you want?
@Chaudhary P Patel: The line ut(n,1)=ut(n,1) replaced the n.th element of the vector ut by the n.th element of the vector ut. This is a waste of time only.
An option to avoid this (see others in the already provided answers):
for n = 1:15
if ut(n) <= U_y(n)
utt(n) = ut(n);
else
utt(n) = 0;
end
end
Or with a proper pre-allocation, to avoid the time-consuming growing of arrays:
utt = zero(15, 1); % The default value is 0 now
for n = 1:15
if ut(n) <= U_y(n)
utt(n) = ut(n);
end
end

Sign in to comment.

 Accepted Answer

If I understand the code correctly, it can be simply stated as:
ut=rand(15,1);
u_y=([0.84;0.384;0.784]);
U_y = [u_y;u_y;u_y;u_y;u_y]; % Create Column Vector
utt = ut; % Copy 'ut' to 'utt'
utt(ut>U_y) = 0 % Set Appropriate Elements To Zero
utt = 15×1
0 0 0.6317 0.7311 0.1069 0.5889 0.5515 0 0.2595 0.3677
No loops!
.

More Answers (1)

Your cleaned code:
ut = rand(15, 1);
uy = [0.84; 0.384; 0.784];
U_y = repmat(uy, 5, 1);
for n = 1:15
if ut(n) > U_y(n)
ut(n) = 0;
end
utt(n) = ut(n);
% ^ insert an index here
end
Remember, that X(k,1) can be written as X(k), which looks a little bit cleaner.
Instead of the loop, you can write:
utt = ut .* (ut <= U_y);
The expression in the parentheses is a vector of 1s and 0s and the elementwise multiplication set the wanted elements to 0.

Categories

Community Treasure Hunt

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

Start Hunting!