Creating dummy variables with if statements

6 ビュー (過去 30 日間)
Philip Gigliotti
Philip Gigliotti 2018 年 9 月 12 日
コメント済み: Rik 2018 年 9 月 19 日
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 Center および File ExchangeMatrix Indexing についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by