How can I create vectors using the IF function?

1 view (last 30 days)
I have five, 8760x1 vectors and I need to create a new vector for each of the five vectors that gives the number 0 for each row if it is not the minimum number of the 5 vectors or if it is the minimum number of the five vectors puts in a number from a separate 8760x1 vector. Thanks for your help.
  3 Comments
James Tursa
James Tursa on 21 May 2015
I am not concerned what the data represents. I simply want to know if the data is in separately named variables, or cells in a cell array, or columns of a 2D matrix, or something else.

Sign in to comment.

Accepted Answer

Walter Roberson
Walter Roberson on 21 May 2015
t = horzcat(Vec1, Vec2, Vec3, Vec4, Vec5);
mt = min(t,2);
eq1 = Vec1 == mt;
eq2 = Vec2 == mt;
eq3 = Vec3 == mt;
eq4 = Vec4 == mt;
eq5 = Vec5 == mt;
Vec1out = 0 * Vec1; %same size and class
Vec2out = 0 * Vec2;
Vec3out = 0 * Vec3;
Vec4out = 0 * Vec4;
Vec5out = 0 * Vec5;
Vec1out(eq1) = Vec6(eq1);
Vec2out(eq2) = Vec6(eq2);
Vec3out(eq3) = Vec6(eq3);
Vec4out(eq4) = Vec6(eq4);
Vec5out(eq5) = Vec6(eq5);
  3 Comments
Guillaume
Guillaume on 21 May 2015
"Careful planning of how data is structured and arranged makes your programming and work much easier."
I could not agree more with Stephen. @Erik, follow this advice (and avoid overuse of for and if) and you'll find that your code is much simpler. In this particular, if instead of five 8760 x 1 vectors you had one 8760 x 5 matrix, the code would simply be:
m = randi([1 5], 8760, 5); %for demo
othervector = randi([10 20], 8760, 1); replacement vector for demo
out = zero(size(m));
isrowmin = bsxfun(@eq, m, min(m, [], 2))
replacement = repmat(othervector, 1, 5);
out(isrowmin) = replacement(isrowmin);
The code is only four lines. One line to prepare the return variable, one line to find which elements of each row is the minimum, and two lines to replace the minimums by your replacement vector.
Erik Hausen
Erik Hausen on 21 May 2015
Edited: Erik Hausen on 21 May 2015
Greatly appreciated! I will make it into 1 matrix.

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!