Creating dummy variables with if statements

11 views (last 30 days)
Philip Gigliotti
Philip Gigliotti on 12 Sep 2018
Commented: Rik on 19 Sep 2018
I'm an expert programmer in Stata but I'm using matlab for a course and I'm very frustrated because it seems so difficult to do even basic things and I can't find any documentation online for even simple operations.
I have 2 column vectors D1, and D2 that give distances of points from a location. I want to create a dummy variable that equals 1 if D1> D2 and - if D2 > D1. I've tried initializing an empty matrix, and then writing this loop:
D3 = zeros (179, 1)
if D1>D2
D3 = 1
elseif D1<D2
D3 = 0
end
But this doesn't change any of the values in D3. I've also tried looping through all the elements of D3 with a for loop but that doesn't do anything either. (Sorry about lack of spacing in the code, I cant even figure our how to use the code editor in this comment tool).
  1 Comment
Stephen23
Stephen23 on 12 Sep 2018
Edited: Stephen23 on 12 Sep 2018
"...I'm very frustrated because it seems so difficult to do even basic things"
MATLAB is not Stata, so forget everything about that. Start by doing the introductory tutorials:
"...and I can't find any documentation online for even simple operations."
When I search for "MATLAB zeros", "MATLAB less than", "MATLAB greater than", "MATLAB if" (these are the simple operations you used in your code) the first results returned are the official documentation pages for those operations. What did you search for?
" I've tried initializing an empty matrix, and then writing this loop:..."
MATLAB is a high-level language, so forget about using low-level loops to solve everything. As Rik Wisselink already showed, logical indexing is a much simpler solution for your task, no loops required:

Sign in to comment.

Answers (1)

Rik
Rik on 12 Sep 2018
Edited: Rik on 12 Sep 2018
You should try the crash course that Mathworks provides for free here. It will teach you the basics so you can find the rest on your own.
The point here is that you should use indexing:
D3 = zeros (179, 1);
for n=1:numel(D3)
if D1(n)>D2(n)
D3(n) = 1;
elseif D1(n)<D2(n)
D3(n) = 0;
end
end
Or use logical indexing in the first place:
D3 = zeros (179, 1);
D3(D1>D2) = 1;
D3(D1<D2) = 0;
  1 Comment
Rik
Rik on 19 Sep 2018
Did this suggestion solve your problem? If so, please consider marking it as accepted answer. It will make it easier for other people with the same question to find an answer. If this didn't solve your question, please comment with what problems you are still having.

Sign in to comment.

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!