Creating dummy variables with if statements

5 次查看(过去 30 天)
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 个评论
Stephen23
Stephen23 2018-9-12
编辑:Stephen23 2018-9-12
"...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:

请先登录,再进行评论。

回答(1 个)

Rik
Rik 2018-9-12
编辑:Rik 2018-9-12
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 个评论
Rik
Rik 2018-9-19
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by