-5

I have a variable var0=rand(50,1). I need to write a function that changes the first 5 lines to 0 and the rest to 1.

Ofcourse, I can simply do this like

var0=rand(50,1)
var0(1:5,1)=0
var0(6:end,1)=1

However I need to do this by using one for, one if and one else clause.

I tried many ways but can't get it working with for, it and else.
Can someone please help with this fairly basic fuction?

Adriaan
  • 17,741
  • 7
  • 42
  • 75
  • 3
    Why? This is a stupid exercise. – sco1 Nov 30 '15 at 14:11
  • 1
    Why would you set such arbitrary requirements? Is this a homework question? – mikkola Nov 30 '15 at 14:11
  • I agree this is stupid, but I have to write some functions that are a followup to this. Please help. –  Nov 30 '15 at 14:12
  • 3
    @excaza It's how some people (i.e., idiots) think coding should be taught. Because apparently recurrence relations that aren't the factorial or Fibonacci sequence are too hard for people. I've encountered this patronizing pedantry before while tutoring computational courses, argued against it, and told to let it go. Assignments like this are an insult to the student's intelligence and education. – TroyHaskin Nov 30 '15 at 14:21
  • I'm voting to close this question as off-topic because it is clearly a homework problem to which no attempt has been made to solve it. – IKavanagh Dec 02 '15 at 10:08

2 Answers2

4

Here's one implementation that meets the requirements:

stupidexercise = true;
topborder = 5;

var0 = rand(50,1);
if stupidexercise
    for ii = 1:topborder
        var0(ii, 1) = 0;
    end

    var0((topborder + 1):end, 1) = 1;
else
    spy
end
sco1
  • 12,154
  • 5
  • 26
  • 48
2

As pointed out by others, this seems a silly assignment. Your approach is more efficient.

var0 = rand(50,1);

for ii = 1:50
    if ii <= 5
        var0(ii) = 0;
    else
        var0(ii) = 1;
    end
end
RPM
  • 1,704
  • 12
  • 15
  • Even though it seems like a minor point considering the silliness of the actual exercise, I just want to point out that it's not good practice to use `i` or `j` as loop variables since they're already reserved for the imaginary unit in MATLAB. – mikkola Nov 30 '15 at 14:17
  • 2
    @mikkola there's an extensive discussion [in this answer](http://stackoverflow.com/questions/14790740/using-i-and-j-as-variables-in-matlab) on not using `i` or `j` – Adriaan Nov 30 '15 at 14:36