Monday 26 February 2018

مربع الجذر من واحد في مصفوفة في ستاتا الفوركس


مرحبا بكم في معهد البحوث الرقمية والتعليم ستاتا التعليمات كيف يمكنني الوصول إلى المعلومات المخزنة بعد تشغيل أمر في ستاتا (النتائج التي تم إرجاعها) بالإضافة إلى الإخراج في يظهر في إطار النتائج، العديد من الأوامر ستاتاس تخزين المعلومات حول الأمر ونتائجها في الذاكرة. وهذا يسمح للمستخدم، وكذلك أوامر ستاتا أخرى، للاستفادة بسهولة من هذه المعلومات. ستاتا يدعو هذه النتائج التي تم إرجاعها. يمكن أن تكون النتائج التي تم إرجاعها مفيدة جدا عندما تريد استخدام المعلومات التي ينتجها أمر ستاتا للقيام بشيء آخر في ستاتا. على سبيل المثال، إذا كنت تريد أن تعني مركز متغير، يمكنك استخدام تلخيص لحساب المتوسط، ثم استخدام قيمة المتوسط ​​المحسوب من خلال تلخيص مركز المتغير. يؤدي استخدام النتائج التي تم إرجاعها إلى إزالة الحاجة إلى إعادة كتابة أو قص ولصق قيمة المتوسط. مثال آخر لكيفية عودة النتائج يمكن أن تكون مفيدة إذا كنت ترغب في توليد القيم المتوقعة للمتغير النتيجة عندما تكون متغيرات التنبؤ في مجموعة محددة من القيم، مرة أخرى هنا، هل يمكن إعادة كتابة المعاملات أو استخدام قص ولصق، ولكن النتائج التي تم إرجاعها جعل المهمة أسهل بكثير. أفضل طريقة للحصول على الشعور كيف النتائج عاد العمل هو القفز الحق في وبدء النظر في واستخدامها. تفتح الشفرة أدناه مثالا لمجموعة البيانات وتستخدم ملخص (مختصر) لإنشاء إحصاءات وصفية لقراءة المتغير. وهذا ينتج الناتج المتوقع، ولكن الأهم من ذلك لأغراضنا، ستاتا لديها الآن نتائج من تلخيص الأمر المخزنة في الذاكرة. ولكن كيف يمكنك أن تعرف ما هي المعلومات المخزنة يتم تضمين قائمة من المعلومات المحفوظة من قبل كل أمر في ملف المساعدة أندور دليل المطبوعة، لذلك يمكن أن ننظر هناك، ولكن يمكنني أيضا أن اكتب قائمة العودة. والتي سوف قائمة كافة النتائج التي تم إرجاعها في الذاكرة. في ما يلي قائمة بالنتائج التي تم إرجاعها، حيث يمكنك مشاهدة كل نتيجة من الاستمارة r (.) حيث تكون علامات الحذف (كوت. كوت) عبارة عن تسمية قصيرة. يمكن أن نرى ملف التعليمات لأمر تلخيص لمعرفة ما كل بند في القائمة، ولكن غالبا ما يكون من السهل معرفة ما هي القيمة التي تم تعيينها إلى أي نتيجة، على سبيل المثال، ص (يعني). وليس من المستغرب يحتوي على متوسط ​​للقراءة (يمكنك التحقق من هذا ضد الإخراج)، ولكن البعض الآخر ليست واضحة، على سبيل المثال ص (سومو). لذلك، قد تحتاج إلى استشارة الدليل إذا كنت تعتقد أنك قد ترغب في استخدامها. في معظم الأحيان سوف تكون عملية سهلة نسبيا لأنك لن تعرف ما هي النتيجة التي تريد الوصول إليها، وسوف تكون تبحث في قائمة لمعرفة ما يتم تخزينه تحت، بدلا من النظر في قائمة ومحاولة لمعرفة ما كل العنصر هو. كما قد تتخيل، أوامر مختلفة، وحتى نفس الأمر مع خيارات مختلفة، تخزين نتائج مختلفة. نلخص أدناه المتغير قراءة مرة أخرى، ولكن إضافة خيار التفاصيل. ثم نستخدم قائمة العودة للحصول على قائمة النتائج التي تم إرجاعها. تماما كما يضيف خيار التفاصيل معلومات إضافية إلى الإخراج، فإنه يؤدي أيضا إلى معلومات إضافية المخزنة في النتائج التي تم إرجاعها. وتشمل القائمة الجديدة جميع المعلومات التي تم إرجاعها بواسطة الأمر سوم أعلاه، بالإضافة إلى التفرطح المنحرف وعدد من النسب المئوية، بما في ذلك الربع الأول (r (p25)) والربع الثالث (r (p75)) والمتوسط ​​(r (p50) ). الآن بعد أن لدينا بعض الشعور ما هي النتائج التي يتم إرجاعها من قبل تلخيص الأمر، يمكننا الاستفادة من النتائج التي تم إرجاعها. من خلال واحدة من الأمثلة المذكورة أعلاه، فإننا سوف يعني مركز المتغير قراءة. وبافتراض أن الأمر الأخير الذي شغلناه كان الأمر الموجز أعلاه، فإن الكود أدناه يستخدم يولد متغيرا جديدا، يحتوي على القيم المتوسطة المتمركزة للقراءة. لاحظ أنه بدلا من استخدام القيمة الفعلية لمتوسط ​​القراءة في هذا الأمر، استخدمنا اسم النتيجة التي تم إرجاعها (أي r (متوسط))، يعرف ستاتا عندما يرى r (يعني) أننا نعني في الواقع القيمة المخزنة في أن متغير النظام. في السطر التالي نلخص القالب المتغير الجديد. في حين أن متوسط ​​لا يساوي بالضبط الصفر، فمن ضمن خطأ التقريب من الصفر، لذلك نحن نعلم أننا قد يعني بشكل صحيح تركز متغير قراءة. وكما يوحي الرمز أعلاه، يمكننا استخدام النتائج التي تم إرجاعها إلى حد كبير بنفس الطريقة التي نستخدم بها الرقم الفعلي. وذلك لأن ستاتا يستخدم r (.) كعنصر نائب لقيمة حقيقية. لمثال آخر على ذلك، قل أننا نريد حساب التباين في القراءة من الانحراف المعياري (تجاهل حقيقة أن تلخيص ترجع التباين في r (فار)). يمكننا أن نفعل ذلك على الطاير باستخدام الأمر العرض كآلة حاسبة. السطر الثاني من التعليمات البرمجية أدناه يفعل ذلك. يمكننا حتى التحقق من النتيجة عن طريق خفض ولصق قيمة الانحراف المعياري عن الإخراج، والذي يتم في الأمر الثالث أدناه. النتائج هي في الأساس نفسه، الفرق الطفيف جدا هو خطأ التقريب لأن التقدير المخزن r (سد) يحتوي على مزيد من أرقام الدقة من قيمة الانحراف المعياري المعروضة في الإخراج. أنواع النتائج التي تم إرجاعها، الفئة - r والفئة الإلكترونية الآن بعد أن عرفت قليلا عن النتائج التي تم إرجاعها وكيفية عملها، فأنت على استعداد لمزيد من المعلومات حولهم. النتائج التي تم إرجاعها تأتي في نوعين رئيسيين، من الدرجة R، والطبقة الإلكترونية (وهناك أيضا s - فئة و C-كلاس النتائج، ولكننا لن نناقشها هنا). والأوامر التي تؤدي التقدير، على سبيل المثال الانحدارات من جميع الأنواع، وتحليل العوامل، وأنوفا هي الأوامر الدرجة الإلكترونية. الأوامر الأخرى، على سبيل المثال تلخيص، وأوامر ربط وبعد تقدير، هي أوامر من الدرجة r. يعتبر التمييز بين الأوامر من الدرجة r و الفئة e أمرا مهما لأن ستاتا يخزن النتائج من الفئة e و الأوامر من الدرجة r في مختلف الاقتباسات. هذا له اثنان من التداعيات لك كمستخدم. أولا، تحتاج إلى معرفة ما إذا كانت النتائج المخزنة في r () أو e () (فضلا عن اسم النتيجة) من أجل الاستفادة منها. إذا لم تكن متأكدا من فئة الأمر الذي قمت بتشغيل هو في، يمكنك إما البحث عنه في ملف التعليمات، أو كوتلوكوت في مكان واحد (باستخدام الأمر المناسب ل قائمة النتائج)، إذا لم يتم تخزين النتائج هناك هم على الأرجح في الأخرى. وهناك ترجيح يحتمل أن يكون أكثر أهمية للفرق في كيفية إرجاع النتائج من الأوامر من الدرجة R والطبقة الإلكترونية هي أن يتم إرجاع النتائج المعادة في الذاكرة فقط حتى يتم تشغيل أمر آخر من نفس الفئة. وهذا هو، يتم استبدال النتائج التي تم إرجاعها من الأوامر السابقة بأوامر لاحقة من نفس الفئة. في المقابل، تشغيل أمر فئة أخرى لن يؤثر على النتائج التي تم إرجاعها. على سبيل المثال، إذا قمت بتشغيل الانحدار، ثم الانحدار الثاني، يتم استبدال نتائج الانحدار الأول (المخزنة في ه ()) تلك التي لالانحدار الثاني (المخزنة أيضا في e ()). ومع ذلك، إذا بدلا من الانحدار الثاني، ركضت أمر ما بعد تقدير، فإن النتائج من الانحدار ستبقى في ه () في حين أن النتائج من أمر آخر تقدير ستوضع في r (). في حين أن هناك فرق بين الاثنين، والاستخدام الفعلي للنتائج من الدرجة R وأوامر الدرجة الإلكترونية هي مشابهة جدا. بالنسبة للمبتدئين، الأوامر موازية، لإدراج نتائج فئة R المخزنة في الذاكرة الأمر هو قائمة الإرجاع. أن تفعل الشيء نفسه لنتائج الدرجة الإلكترونية قائمة إريتورن الأمر. وعلاوة على ذلك، باستثناء الاختلاف في اصطلاحات التسمية (r () مقابل e ())، يتم الوصول إلى النتائج بنفس الطريقة. يوضح المثال أدناه هذا، أولا نراجع الكتابة على الإناث والقراءة. ثم استخدم قائمة إريترن للنظر في النتائج التي تم إرجاعها. تتضمن قائمة النتائج التي تم إرجاعها للرجوع عدة أنواع من النتائج التي تم إرجاعها ضمن العناوين الرأسية، وحدات الماكرو، المصفوفات والوظائف. سنناقش أنواع النتائج التي تم إرجاعها أدناه، ولكن في الوقت الحالي سوف نعرض كيف يمكنك استخدام النتائج التي تم إرجاعها بنفس الطريقة التي استخدمنا بها النتائج التي تم إرجاعها من الملخص. على سبيل المثال، طريقة واحدة لحساب تباين الأخطاء بعد الانحدار هي تقسيم المجموع المتبقي من المربعات حسب درجات الحرية الكلية (أي n-1). يتم تخزين المبلغ المتبقي من المربعات في e (رسس) ويتم تخزين n للتحليل في e (N). أدناه نستخدم الأمر العرض كآلة حاسبة، جنبا إلى جنب مع النتائج التي تم إرجاعها لحساب التباين من الأخطاء. كيف يتم إرجاع النتائج: سكالارس، السلاسل، المصفوفات والوظائف كما ذكر أعلاه، بالنسبة لكل من الأوامر من الدرجة R و الفئة E، هناك أنواع متعددة من النتائج التي تم إرجاعها، بما في ذلك النتائج، السلاسل، المصفوفات، والوظائف. في قوائم النتائج التي تم إرجاعها، يتم إدراج كل نوع تحت العنوان الخاص به. النتائج المدرجة تحت عنوان كوتسكالارسكوت هي مجرد أن، قيمة رقمية واحدة. ويناقش استخدامها أعلاه، لذلك نحن لن نقول بعد الآن عنهم في هذا القسم. النتائج التي تم إرجاعها ضمن كوتوماكروسكوت عموما سلاسل تعطي معلومات حول الأمر الذي تم تشغيله. على سبيل المثال، في النتائج التي تم إرجاعها للتراجع الموضح أعلاه، e (كمدلين) يحتوي على الأمر الذي أصدره المستخدم (بدون أي اختصار). وتستخدم هذه عادة في برمجة ستاتا. النتائج المدرجة تحت كوتماتريسسكوت هي، كما تتوقعون، المصفوفات. في حين أن قائمة النتائج التي تم إرجاعها من قبل قائمة العودة وقائمة إرتورن تظهر لك القيم التي اتخذتها معظم النتائج التي تم إرجاعها، وهذا ليس عملي مع المصفوفات، بدلا من ذلك يتم سرد أبعاد المصفوفات. لرؤية محتويات المصفوفات يجب عليك عرضها باستخدام أوامر المصفوفة. نقوم بذلك أدناه مع مصفوفة المعاملات (e (b)) باستخدام قائمة مصفوفة الأوامر e (b). (لاحظ أن هناك طريقة أخرى للوصول إلى المعاملات وأخطاءها القياسية بعد تناسب نموذج، وهذا ما نوقش أدناه). إذا كنا نود إجراء عمليات مصفوفة على المصفوفات عاد، أو ترغب في الوصول إلى العناصر الفردية للمصفوفة، يمكننا نقل المصفوفة المخزنة كنتيجة عاد إلى مصفوفة ستاتا العادية. يتم ذلك في السطر الأخير من بناء الجملة أدناه. وأخيرا، فإن النتائج التي يتم إرجاعها تحت عنوان كوتفونكتيونسكوت تحتوي على وظائف يمكن استخدامها بطريقة مشابهة لوظائف ستاتا الأخرى. الدالة الأكثر شيوعا التي يتم إرجاعها بواسطة أوامر تقدير ستاتا هي على الأرجح e (سامبل). وتمثل هذه الدالة العينة المستخدمة في تقدير التحليل الأخير، وهذا مفيد لأن مجموعات البيانات كثيرا ما تحتوي على قيم مفقودة مما يؤدي إلى عدم استخدام جميع الحالات في مجموعة البيانات في تحليل معين. على افتراض أن آخر أمر تشغيل تقدير كان انحدار الكتابة على الإناث والقراءة المبينة أعلاه، السطر الأول من التعليمات البرمجية أدناه يستخدم ه (عينة) للعثور على متوسط ​​القراءة بين تلك الحالات المستخدمة في النموذج. السطر الثاني من التعليمات البرمجية يستخدم e (عينة) لإنشاء متغير جديد يسمى علم يساوي 1 للحالات التي استخدمت في التحليل، و صفر خلاف ذلك. (ملاحظة نظرا لأن مجموعة بيانات المثال لا تحتوي على بيانات مفقودة، يتم تضمين جميع الحالات في التحليل، والعلم ثابت على قدم المساواة.) المعاملات وأخطاءها القياسية كما نوقش أعلاه، بعد واحد يناسب نموذج والمعاملات ومعيارها يتم تخزين الأخطاء في e () في شكل مصفوفة. تسمح هذه المصفوفات للمستخدم بالوصول إلى المعاملات، ولكن ستاتا يمنحك طريقة أسهل للوصول إلى هذه المعلومات من خلال تخزينها في متغيرات النظام b و سي. للوصول إلى قيمة معامل الانحدار بعد الانحدار، كل واحد يحتاج إلى القيام به هو نوع بفارنام حيث فارنام هو اسم متغير التنبؤ الذي تريد معامله. للوصول إلى الخطأ القياسي، يمكنك ببساطة كتابة سيفارنام. للوصول إلى معامل والخطأ القياسي من ثابت نستخدم بكونس و سيكونس على التوالي. أدناه نحن تشغيل نفس نموذج الانحدار ركضنا فوق (حذف الناتج)، وذلك باستخدام الإناث وقراءة للتنبؤ الكتابة. وبمجرد أن نقدر النموذج، نستخدم الأمر عرض لإظهار أن القيم في b تساوي معاملات الانحدار لدينا. وأخيرا، فإننا نحسب القيمة المتوقعة للكتابة عندما يكون لدى الإناث (الإناث 1) طالب درجة القراءة من 52. محتوى هذا الموقع لا ينبغي أن يفسر على أنه تأييد لأي موقع على شبكة الإنترنت، والكتاب، أو منتج البرمجيات معين من قبل جامعة كاليفورنيا. مقدمة في ماتا ماتا هي لغة مصفوفة بنيت في ستاتا، مماثلة في العديد من الطرق ل R، ماتلاب أو غوس. إلا أن لديها بعض الميزات الفريدة والمثيرة للاهتمام. واحد هو أنه لغة مجمعة بدلا من تفسير، مما يحسن الأداء. كما تم موازاة في ستاتيمب (متوفرة على جميع خوادم لينكس سك و كوندور) الذي يحسن بشكل كبير الأداء. من ناحية أخرى ماتا هو جديد إلى حد ما، ولم يقم بعد كوتكوت أونكوت في سك، لذلك ليس لدينا أي مقارنات في العالم الحقيقي لتقديم. ماتا ليست بديلا عن ستاتا، كما أنها لا تعتزم أن تكون مجموعة إحصائية قائمة بذاتها. بل هو أداة التي تستخدم على أفضل وجه تكملة ل ستاتا (أو ساس أو سبس)، للقيام بهذه الأشياء ستاتا لا تفعل بشكل جيد من تلقاء نفسها. وعلى وجه الخصوص، لا تعمل شركة ماتا في سياق مجموعة بيانات واحدة، مما يعطيها مرونة إضافية. ولكن يجب أن لا تحاول أن تتعلم ماتا إلا إذا كنت على دراية بالفعل ستاتا أو حزمة إحصائية أخرى. ماتا هي لغة مستوفاة نسبيا. يتم قضاء الكثير من وقتك في ستاتا (أو ساس أو سبس) باستخدام البرامج المضمنة، وإيجاد مجرد مجموعة مناسبة من الخيارات للحصول على ستاتا أن تفعل ما تريد. في ماتا سوف تأخذ السيطرة المباشرة، وتقول ماتا ما تريد القيام به خطوة بخطوة. (محسن ماتا، الذي سنناقشه مطولا، هو استثناء ملحوظ). وهذا يعني أن الأمور البسيطة عادة ما تكون أكثر تعقيدا في ماتا مما كانت عليه في ستاتا، ولكن ماتا لديها قيود أقل. هذه المقالة مكتوبة في المقام الأول للأشخاص الذين لديهم خبرة كبيرة باستخدام ستاتا، ساس أو سبس بناء الجملة، ولكن لا لغات البرمجة الأخرى. وبالتالي سيكون هناك الكثير من التركيز على تعلم كيفية القيام بالأشياء المفيدة من خلال التلاعب المصفوفات، والعديد من الأمثلة تهدف إلى إعطاء تجربة القيام بذلك فضلا عن توضيح مفهوم معين. ماتلاب و غوس قدامى المحاربين قد تجد أنها يمكن تخطي هذه المقاطع، مع التركيز على ما هو جديد لهم. سيجد المبرمجون C أن ماتا يقلد C كلما كان ذلك ممكنا، حتى يتمكنوا ربما تخطي المقاطع على البرمجة القياسية يبني مثل الحلقات. ولكن بغض النظر عن الخلفية الخاصة بك، وسوف تتعلم أكثر من ذلك بكثير إذا كنت تقرأ هذه المادة على جهاز الكمبيوتر، مع تشغيل ستاتا، ونوع فعلا في الأمثلة. ماتا يعمل داخل ستاتا، وذلك من أجل استخدام ماتا يول تحتاج إلى معرفة كيفية تشغيل برنامج ستاتا، ودعا ملف دو. إذا كنت تستخدم أبدا ستاتا، يرجى قراءة القسم على الملفات لا في مقدمة ل ستاتا. ستاتا التفاعلية (أي بدء تشغيله ونوع الأوامر) هو وسيلة رائعة للتعلم وهذا هو كيف ستفعل الأمثلة في هذه المقالة. ولكن للعمل الحقيقي سوف تريد أن تكتب كل شيء في القيام الملفات. هناك عدة أمثلة لملفات مقترنة بهذه المقالة. هناك روابط لهم في النص كما يتم استخدامها. ومع ذلك، إذا كنت تستخدم خادم لينكس سك قد ترغب في نسخ كل منهم في وقت مبكر. للقيام بذلك اكتب ما يلي في موجه لينكس: مكدير ماتاكلاس سد ماتاكلاس كب usrglobalwebssccpubsfiles4-26. وترد معظم الأوامر يول نوع كما تقرأ أيضا في mataclass. do. تم العثور على المثالين الرئيسيين في ex1.do و ex2.do. أساسيات ماتا لبدء ماتا، ابدأ أولا ستاتا ثم اكتب في إطار الأمر. ستاتا ثم التبديل إلى وضع كوتماتا. كوت من السهل أن ننسى أي وضع كنت في، ولكن إذا نظرتم بعناية في الجزء السفلي من نافذة الاستعراض، حيث ترى عادة فترة يول الآن نرى القولون. وبطبيعة الحال عند بدء تشغيل ماتا ثيريس خط أفقي كبير أن يقول ماتا ولكن لن يكون مرئيا لفترة طويلة. هذا الشريط أيضا يذكرك من أمر مفيد آخر: للخروج من وضع ماتا، اكتب بينما يتم تنظيم ستاتا حول الأوامر، ويتم تنظيم ماتا حول qustatements. quot على سبيل المثال، يمكنك ببساطة كتابة وسوف يعود ماتا تخزين النتائج في متغير هو تماما كما سهلة: لاحظ أنه لم يكن هناك أي إخراج هذه المرة. إذا كنت تريد أن ترى قيمة x، ببساطة اكتب: وسوف تحصل على 4 العودة. مشغلي المصفوفة في الأمثلة السابقة لدينا، عملت علامة زائد كمشغل: اعترف ماتا عليه قول الاقتباس من الشيء قبل علامة زائد والشيء بعد علامة الجمع وإجمالي them. quot كما يعرف ماتا مشغلي المصفوفة التي تنفذ التلاعب مصفوفة. العمود والصف الانضمام يتم تعريف الفاصلة باسم المشغل جوينكوت كوتكولومن، أو اقتباس الأشياء قبل وبعد الفاصلة ووضعها بجانب كل other. quot وهذا يعني يتم تفسيرها من قبل ستاتا كما مصفوفة مع صف واحد وعمودين. في الواقع، اكتبه وسوف يكون الإخراج: شرطة مائلة مائلة (وليس هو تقسيم) هو مشغل الجذر النقطية، أو اقتباس الشيء قبل مائل مائل وكومة على الجزء العلوي من الشيء بعد it. quot وهكذا هو مصفوفة مع صفين وعمود واحد: الأشياء التي سيتم تشغيلها لا تقتصر على العددية، حتى تتمكن من بناء المصفوفات. رسائل الخطأ هناك حدود: لتيستمتغ: 3200 خطأ كونفورميبيليتي r (3200) لا يمكنك إجراء مصفوفة يحتوي الصف الأول على عمودين ولكن الصفين الثاني والثالث له عمود واحد. ستاتا يدعو هذا خطأ في كونفورمابيليتي، فئة التي تشمل أيضا أشياء مثل محاولة مضاعفة المصفوفات حيث عدد الأعمدة من المصفوفة الأولى يختلف عن عدد الصفوف من الثانية. هذا أيضا خطأ كورتونتيمكوت. عندما تعطي ماتا بيانا، أول شيء يقوم به هو ترجمة البيان إلى رمز البايتة. عند هذه النقطة ماتا لا تبحث في كميات محددة ليتم التلاعب بها. كل ما يراه هو اقتراب شيء بجانب شيء آخر، ثم كومة أن على رأس اثنين من الأشياء الأخرى. كوت هذا أمر منطقي، وبالتالي فإن البيان يجمع بنجاح. فقط عندما تشغيل التعليمات البرمجية لا تلاحظ ماتا أن الأشياء التي سيتم مكدسة لها أعداد مختلفة من الأعمدة. يتم إنشاء خطأ وقت تجميع عندما لا معنى له معنى بغض النظر عن الكميات التي سد العجز في ذلك. على سبيل المثال، تعبير غير صالح r (3000) أخطاء وقت الترجمة هي دائما رمز الخطأ 3000، ولا تتضمن لتيستمتغ. ملاحظة ما إذا كان خطأ خطأ وقت تجميع أو خطأ وقت التشغيل يمكن أن تساعدك في العثور على المشكلة. إذا كان وقت التشغيل، كما تعلمون ماتا فهمت على الأقل التعليمات البرمجية الخاصة بك (على الرغم من ثيريس أي ضمان أنه يفهم أنه يعني نفس الشيء كنت أفهم أن يعني) وكان شيئا عن الكميات المحددة التي كانت تعمل مع التي تسببت في المشكلة. إذا كان وقت تجميعها، رمز حتى لا معنى له ماتا. الأقواس كما كنت تجميع المصفوفات كنت موضع ترحيب لتشمل الأقواس للمساعدة في توضيح الأمور. في الغالب لصالحك: كلها هي نفسها ل ماتا، ولكن إذا كان واحد منهم تبدو أكثر وضوحا لك بكل الوسائل استخدام هذا النمط في جميع البرامج الخاصة بك. (أنا يحدث ليكون من محبي الثالث.) مجموعة مشغلي مجموعة أخرى من الأدوات المفيدة لإنشاء مصفوفات هي مشغلي النطاق. ال. المشغل يخلق سلسلة بدءا من عدد على اليسار حتى الرقم على اليمين ويجعلها في متجه الصف. ال. المشغل يفعل الشيء نفسه ولكن يضعها في ناقلات العمود. لا يقتصر على الأعداد الصحيحة، ومع ذلك: لاحظ أن الرقم على اليمين ليست مضمونة لتكون جزءا من سلسلة الناتجة. وبطبيعة الحال يمكن حفظ نتائج البيانات المصفوفة في المتغيرات تماما مثل البيانات الأخرى. على سبيل المثال: لاحظ كيف يبدو تعريف z كثيرا مثل العبارة التي جربناها سابقا والتي أعطت خطأ وقت التشغيل. يتم تشغيله الآن لأن x و y يحتويان على عمودين. ثاتس لماذا كان خطأ وقت التشغيل وليس خطأ وقت الترجمة: نظرا للمدخلات الصحيحة يمكن أن يعمل البيان. المشغلون الحسابيون يتعرف المشغلون الحسابيون المعياريون عندما يكون أحد الوسيتين أو كليهما مصفوفة، ويتصرفان وفقا لذلك. وهذا يشمل الجمع والطرح، المصفوفة مرات العددية، ومضاعفة مصفوفة كاملة. ومع ذلك، هناك أيضا مشغلي كوتولونكوت التي عنصر العمل حسب العنصر. ل الجمع والطرح فإنه لا فرق، لأنهم عنصر من عنصر على أي حال. لكنه يجعل قدرا كبيرا من الاختلاف مع الضرب. ضع في اعتبارك ما يلي: المشغلين المنطقيين يتم تعريف المشغلين المنطقيين مثل أكبر من، أقل من، ومساوي أيضا في كل من إصدارات المصفوفة والقولون (لاحظ أن المشغل يساوي، بدلا من التخصيص). ومع ذلك، لا يحتوي ماتا على نوع متغير منطقي. وهكذا (كما في ستاتا) مشغلي منطقية إرجاع واحد ل صحيح و صفر ل كاذبة. إذا قارنت مصفوفتين باستخدام معيار أكبر من أو أقل من أو يساوي، ترجع ماتا واحدة إذا وفقط إذا كان الشرط صحيح لجميع عناصر المصفوفتين. وإلا فإنه يعود الصفر هؤلاء المشغلين يمكن أن تعمل فقط على المصفوفات من نفس الحجم. في شكل القولون، والنتيجة هي مصفوفة تحتوي على كل المقارنات عنصر تلو الآخر. يسمح شكل القولون بمزيد من المرونة حول أحجام المصفوفات التي يجب مقارنتها. إذا كانت إحدى الوسيطات عبارة عن متجه نسبي أو متجه صف أو متجه عمود، فسيتم تكرارها حسب الحاجة بحيث تتطابق مع المصفوفة الأخرى. مشغل تبديل هو اقتباس واحد الحق (). وهو يعمل على كائن واحد فقط، واحد إلى يسارها، ويعيد تبديله: لا يوجد عامل معكوس، ومع ذلك. ويتم عكس من قبل وظائف. سوبسكريبتس للإشارة إلى عنصر معين في مصفوفة، ضع رقم الصفوف والأعمدة بين قوسين مربعين بعد اسم المصفوفة. وبالنظر إلى المصفوفة x المعرفة أعلاه، x1،1 هو 1. x1،2 هو 2. الخ. يمكن استخدام سوبسكريبتس على جانبي علامة متساوية: إذا كان مصفوفة متجه صف أو عمود، يمكنك استخدام واحد فقط سوبسكريبت. كوتيميسينغكوت للصف أو عمود رقم يؤخذ على أنه يعني كل الصفوف أو الأعمدة. يمكنك استخدام إما الفترة القياسية لفقدان أو ببساطة ترك عدد خارج. وهكذا يمكنك أيضا استبدال أي عدد مع متجه صف أو عمود (و ستاتا لا يهتم أي واحد كنت تستخدم). ومع ذلك، مطلوب هذه الأقواس الوقت لذلك ماتا يعرف أين تنتهي قائمة الصفوف والأعمدة تبدأ. يمكنك تكرار الصفوف أو الأعمدة، وخلط النظام، أو حتى إنشاء مصفوفات أكبر من الأصلي. ناقلات محددة مسبقا هي أيضا على ما يرام: لاحظ أن استخدام النصوص الناقلة مثل هذا سيكون أسرع من ضرب من خلال مصفوفة التقليب. نطاقات التسجيلات يشير ماتا إلى النصوص التي استخدمناها حتى الآن كمخطوطات كوتليستكوت. تم سرد كل عنصر أردنا صراحة (حسنا، باستثناء المفقودين معنى كوتالكوت). ولكنك غالبا ما تريد تحديد نطاق من الصفوف والأعمدة. ثيرس لا تحتاج كثيرا ل نطاقات مع المصفوفات الصغيرة، لذلك تبدأ من خلال خلق مصفوفة أكبر: خذ لحظة لمحاولة معرفة كيف عملت هذه قبل قراءة أبعد من ذلك. السطر الأول يعرف x1 متجه صف باستخدام عامل التشغيل المدى. والثاني يعرف متجه العمود x2، مرة أخرى باستخدام عامل التشغيل المدى ولكن ضرب النتيجة بمقدار عشرة. الثالث ثم يعرف x عشر نسخ من x1 مكدسة على رأس بعضها البعض بالإضافة إلى عشر نسخ من x2 وضعت بجانب بعضها البعض. والنتيجة هي عشرة مصفوفة عشرة التي تذهب من 11 إلى 110، الأمر الذي سيجعل من السهل معرفة أي الصفوف والأعمدة التي تم استخراجها في الأمثلة القليلة المقبلة. (نعم، هناك طرق أسهل للقيام بذلك باستخدام وظائف حلقات أندور، ولكن نحن تغطيها حتى الآن.) طريقة واحدة لاستخراج مجموعة من الصفوف والأعمدة من x هو استخدام مشغلي النطاق ضمن البرامج الفرعية القائمة. وهكذا للحصول على صفوف 3-7 والأعمدة 4-8 هل يمكن أن تفعل: هذا هو بالضبط ما يعادل لكتابة: النصوص الحقيقية النطاق، ومع ذلك، هي مختلفة. لشيء واحد، أنها ترد في أقواس مربعة وحرف الأنبوب (التحول إلى الوراء). هناك عنصران، مفصولين بشرطة مائلة عكسية: الصف والعمود في الزاوية اليسرى العليا من النطاق المطلوب، والزاوية اليمنى السفلى من النطاق المطلوب. وبالتالي فإن ما يعادل التفكير بها على أنها استبدال الحبار أربعة إلى سبعة وأعمدة من ثلاثة إلى ثمانية مع كوتيفيريثينغ بين الصف الرابع، العمود الثالث والصف السابع، العمود الثامن، شاملة. يمكن المفقودين يعني عدة أشياء في مجموعة النصوص. إذا استخدمت في تحديد الزاوية اليسرى العليا، فهذا يعني إما الصف الأول أو العمود الأول. إذا استخدمت في تحديد الزاوية اليمنى السفلى، فهذا يعني إما الصف الأخير أو العمود الأخير. وهكذا هو ببساطة كل من x. ثيريس أيضا أي قاعدة تقول الزاوية العلوية اليسرى والسفلية اليمنى لا يمكن أن يكون على نفس الصف أو العمود. وهذا يعني الكرو ثلاثة، من العمود الثالث إلى النهاية. كوت الحصول على البيانات الخاصة بك من ستاتا إلى ماتا في معظم الوقت كنت لن تكون خلق المصفوفات باليد. بدلا من ذلك تريد أن تجعل المصفوفات التي تحتوي على البيانات لديك بالفعل في ستاتا. أنت أيضا من المرجح أن تريد أن تأخذ نتائج ماتا الخاص بك ونسخها إلى مجموعة بيانات ستاتا الخاص بك. السؤال الأول الذي تحتاج إلى الإجابة عليه هو ما إذا كنت ترغب في تقديم نسخة جديدة من البيانات الخاصة بك، أو ما إذا كنت تريد أن يكون ماتا العمل مع البيانات ستاتا مباشرة. يمكن ماتا تعريف المصفوفات التي هي في الواقع كوتيسكوت بيانات ستاتا الخاص بك. التفكير في وجهة نظر كما مجرد إعطاء بيانات ستاتا اسم ماتا يمكن استخدامها. تستخدم المشاهدات كمية تافهة من الذاكرة حتى إذا كانت بياناتك كبيرة جدا. إذا قمت بتغيير جداول مصفوفة عرض، يتم أيضا تغيير بيانات ستاتا. إذا قمت بعمل نسخة من البيانات بدلا من ذلك يمكنك إجراء تغييرات والحفاظ على سليمة سليمة، ومع ذلك سوف تستخدم ضعف الذاكرة. لجعل نسخ من البيانات الخاصة بك ستستخدم عائلة ستداتا من الوظائف. أبسط وأسرع هو ستداتا. يتم استخدامه للحصول على رقم واحد من مجموعة البيانات الخاصة بك. فإنه يأخذ اثنين من الحجج: رقم المراقبة ورقم متغير. فكر في مجموعة البيانات الخاصة بك كمصفوفة بالفعل، ورقم المتغير هو ببساطة رقم العمود للمتغير الذي تريده. لرؤية هذا في العمل، نهاية الأولى ماتا عن طريق كتابة نهاية. تحميل السيارات سبيل المثال مجموعة البيانات، قائمة الملاحظة واحد، والعودة إلى ماتا: نهاية سيسيسيوس السيارات ل في 1 ماتا الآن الحصول على سعر السيارة الأولى عن طريق كتابة: والنتيجة ستكون 4099، الذي يطابق ما قمت سرد فقط. حاول بعض المتغيرات الأخرى للتأكد من أنك حصلت على الفكرة. لاحظ أنه إذا حاولت الحصول على العمود الأول ستحصل على قيمة مفقودة. وذلك لأن ستداتا هو فقط للبيانات الرقمية. لسلاسل، استخدم ستسداتا الذي يعمل في حد كبير بنفس الطريقة. ماتا يمكن البحث عن أرقام الأعمدة بالنسبة لك باستخدام وظيفة ستفاريندكس. يأخذ اسم المتغير الذي تريده ويقوم بإرجاع الفهرس. ومع ذلك، فإن هذه العملية تبطئ الأمور قليلا. لاحظ أنك موضع ترحيب لاستخدام إخراج دالة واحدة كوسيطة لوظيفة أخرى: إذا كنت تريد أكثر من قيمة واحدة، فاستخدم ستداتا. ستداتا يمكن استخدامها تماما مثل ستداتا (على الرغم من أن في هذه الحالة ستداتا أسرع). ومع ذلك، ستداتا أكثر مرونة حول الحجج التي سيقبلها. قد يكون رقم الصف مفقودا، وفي هذه الحالة يتم إرجاع جميع الملاحظات. ويمكن أيضا أن يكون ناقلا العمود، وفي هذه الحالة فقط يتم إرجاع الملاحظات المحددة. ويمكن أيضا أن يكون مصفوفة مع عمودين. ثم يمثل كل صف مجموعة من الملاحظات. المفقود في هذه الحالة يفسر على أنه الملاحظة الأخيرة. ويمكن أيضا أن يكون رقم العمود مفقودا (جميع المتغيرات) أو متجها يسرد المتغيرات المطلوبة. ويمكن أن يقبل أيضا أسماء المتغيرات بدلا من أرقامها، على الرغم من أن هذا سيكون أبطأ. لا يسمح لك بتحديد نطاقات مثل يمكنك للصفوف. مثل ستداتا. ستداتا لا يمكن التعامل مع السلاسل. ولكن هناك ستسداتا ما يعادلها. جرب ما يلي: ستداتا (.) ستداتا ((1،3)، 2) ستداتا (1، (2،4)) ستداتا (1، (كوتراسيكوت، كوتريبوت)) ستسداتا (.، 1) وبطبيعة الحال كل هذه النتائج يمكن أن تكون المخزنة في المصفوفات لاستخدامها في المستقبل. ستداتا يمكن أيضا أن تأخذ الوسيطة الثالثة: متغير التحديد. ويمكن أن يكون ذلك إما الفهرس أو اسم المتغير، وإذا كان محددا، فإن الملاحظات التي لا يعاد فيها هذا المتغير هي صفر فقط. اختيار 0 كمتغير المحدد له معنى خاص: في هذه الحالة سيتم استبعاد الملاحظات إذا كانت لديهم قيمة مفقودة لأي متغير محدد. ستفيو يجعل المشاهدات على البيانات الخاصة بك بدلا من نسخها، ولكن يمكنك تحديد الصفوف والمتغيرات باستخدام نفس الطرق بالضبط كما ستداتا. ومع ذلك، ستفيو يعطيك النتائج بطريقة مختلفة. مع ستداتا. المصفوفة التي تريدها هي وظيفة ستداتا التي تم إرجاعها. يمكنك ثم تخزين النتائج أو ببساطة السماح لهم أن يتم عرضها على الشاشة. مع ستفيو. فإن الوظيفة نفسها لا تعيد شيئا. بدلا من ذلك تحتاج إلى تمرير في مصفوفة التي سيتم استبدالها مع وجهة نظر قمت بتحديد. واحد الصيد هو أن المصفوفة يجب أن توجد قبل أن تمر عليه. لا يهم كم هو كبير - في الواقع سيتم استبدالها تماما - ولكن إذا حاولت تمرير مصفوفة لاستعراض أن لم يتم تعريفها بطريقة أو بأخرى الحصول على خطأ وقت التشغيل. طريقة سهلة واحدة هي ببساطة وضع المصفوفة التي تريد استخدامها إلى الصفر قبل تمريرها في. يمكنك حتى القيام بذلك داخل دعوة وظيفتك: x و n تبدو الآن مثل المصفوفات العادية، ولكن نضع في اعتبارنا أنها في الواقع وجهات النظر . إذا كان الهدف الخاص بك في استخدام وجهة نظر هو حفظ الذاكرة، عليك أن تكون حريصا على عدم إجراء نسخ منه. لا يؤدي إلى إنشاء طريقة عرض جديدة. أنه يخلق مصفوفة جديدة تحتوي على قيم x نسخة. بشكل أكثر دقة، يخلق نسخة من العمود جث من x. إذا كنت بحاجة إلى عمود معين من x، يمكنك فقط إنشاء طريقة عرض جديدة: ثيريس لا يوجد حد لعدد المشاهدات المختلفة التي يمكن إعدادها لنفس البيانات. الحصول على البيانات الخاصة بك من ماتا إلى ستاتا إذا كان كل ما تريد القيام به هو تغيير قيم المتغيرات الحالية، وجعل وجهة نظر وتغيير في الإرادة. ولكن إذا كنت ترغب في إضافة متغيرات جديدة ستحتاج إلى بضع المزيد من الوظائف. ستادفار يضيف متغير جديد. يستغرق الأمر وسيطتين: نوع المتغير واسم المتغير. فإنه يقوم بإرجاع مؤشر المتغير، على الرغم من تخزين أن لاستخدامها في المستقبل هو اختياري. يتيح إنشاء متغير جديد: وزنمغ (لذلك، جنيه-ميل للغالون الواحد، وحدة يمكن لمهندس فقط أحب). لاحظ أن المصفوفة تسمى مبغ الآن عرض لكل الصفوف من متغير مبغ. ستفيو (الوزن 0. كوتكسكوت) بمغويت: مبغ ستادفار (كوتلونغكوت، كوتمغكوت) ستستور (.، كوتمغكوت، بمغ) لاستكشاف هذا المتغير الجديد باستخدام أدوات ستاتا التي تعرفها، نوع النهاية. وبطبيعة الحال هذا هو بديل أخرق غير عادية ل بمغببغويت طويلة جنرال هذا يؤدي إلى مبدأ عام: استخدام ماتا لما لها جيدة في، و ستاتا لما لها جيدة في. هناك مجموعة واسعة من الوظائف الأخرى التي يمكنك استخدامها للاتصال بين ماتا و ستاتا، بما في ذلك إضافة الملاحظات والحصول على أو وضع وحدات الماكرو المحلية، ه () و r () ناقلات، وأكثر من ذلك بكثير. راجع الدليل للتفاصيل. إنقاذ وتحميل البيانات ماتا في معظم الأحيان الهدف من برنامج ماتا هو أن تأخذ البيانات ستاتا الخاص بك، والعثور على نتيجة، ومن ثم إما عرضه أو وضعها مرة أخرى في البيانات ستاتا الخاص بك. ومع ذلك، يمكنك حفظ ماتا المصفوفات أنفسهم إذا كنت في حاجة إليها. لحفظ مصفوفة، اكتب ماتا ماتساف اسم الملف ماتريكسليست استبدال اسم الملف مع اسم الملف الذي تريد إنشاء. ستاتا إضافة. mmat إلى اسم الملف تلقائيا. استبدال ماتريكسليست مع واحد أو أكثر من المصفوفات التي تريد حفظها (فصل بينها بمسافات) أو مع علامة النجمة () لحفظ كافة المصفوفات الموجودة حاليا في الذاكرة. لتحميل المصفوفات يويف المحفوظة سابقا، اكتب ماتا ماتوس اسم الملف هذا سيتم تحميل كافة المصفوفات المخزنة في اسم الملف. سيقبل كلا الأمرين خيار الاستبدال. ل ماتساف. وهذا يسمح ماتا الكتابة فوق الملف الموجود على القرص. ل ماتوس. وهذا يسمح ماتا الكتابة فوق المصفوفات الموجودة في الذاكرة مع نفس أسماء المصفوفات في الملف. هذه الأوامر مخصصة للاستخدام التفاعلي ولا يمكن استخدامها في الوظائف. إذا كنت بحاجة إلى حفظ المصفوفات داخل وظيفة، تحقق من فوبين. fputmatrix. fgetmatrix. و فكلوس. Hierarchical Data Hierarchical data has always been a bit awkward to work with in Stata, or any other statistical program that uses a single data matrix. A typical example would be individuals living in households: should each household be one observation, or each individual Either way there are inefficiencies. In Mata you can have it both ways: one matrix of individuals and one matrix of households. The key is linking them together, but subscripts make that easy. As an example, take a look at the hh Stata data set. which is in Stata format. It consists of six individuals living in three households. hh is the household ID, hhType is the type of household, and hhInc is the household income. age and female are individual variables. This data is in the long form, with one observation for each individual, which means that the household variables must be duplicated. end use hh, replace l Now enter mata and load the hh Mata data set . mata mata matuse hh hh ind It contains two matrices, ind and hh. hh contains the household level variables ( hhType and hhInc ). ind contains the individual variables ( age and female ) plus the household ID. Note however, that hh does not contain an ID: the row number is an implicit ID. For example, if you wanted to know what type of household person number two lives in, youd use: ind2,3 is the household ID of the second person, or the row in the hh matrix. Column one of hh is the household type. Of course a regression model may need a single matrix just like Stata does. You can easily recreate the matrix as Stata views it with: Here ind.,3 is a column vector listing which row we want from hh for each row of ind. The resulting rows from hh are then placed next to ind to create x . Matrix Functions Mata has a very large number of matrix functions built into it. This section will hit some of the most useful. Creating Matrices The I function can take one or two arguments. If it is given one argument, it will return an identity matrix of size equal to the argument it was given. If it is given two arguments, it will return a matrix with that number of rows and columns which is full of zeroes except for ones along the principal diagonal. The J function creates a matrix of constants. It takes three arguments: the number of rows of the matrix to be created, the number of columns, and what to put in the matrix. The last argument can be of any type. The e function creates unit vectors: row vectors with a one in one column and zeroes everywhere else. It takes two arguments: the location of the one, and the size of the row vector. Thus you could create an identity matrix by combining e s, though the I function would of course be much easier. The uniform function returns a matrix filled with random numbers distributed uniform(0,1). The size is specified in the same way as with the J function. If youre putting together a matrix which will be symmetric, the makesymmetric function can take care of half the work for you. You put together the lower triangle, and makesymmetric will copy it to the upper triangle (replacing what was there before). It takes one argument, a matrix, and returns the symmetric version. x(1,2)(3,4) ymakesymmetric(x) y Theres a second version, makesymmetric which returns nothing but changes the input matrix instead: The sort function returns a sorted matrix. It takes two arguments: the matrix to sort, and the column(s) to sort by. Note that sort is not a quotstablequot sort. If there are any ties, they will be resolved randomly. Repeat sort(x,1) enough times and you should see some cases when the original second row becomes the first row and others where it stays the second row. If the second argument is a row vector, the matrix will be sorted by the first column listed, then ties resolved by the second column, etc. sort does not change the matrix it is given--it returns a copy. If youd prefer to sort the original matrix without making a copy, use sort . jumble and jumble are the opposite of sort and sort. They take just one argument, a matrix, and put its rows in a random order. Sizes of Matrices rows. cols. and length all take one argument, a matrix. They return the number of rows, the number of columns, and the total number of elements (rowscolumns) in that matrix respectively. rows(x) cols(x) length(x) These can be very useful in for loops where you want to loop over your entire matrix but dont know ahead of time what size it will be. Of course matrices can have missing values just like ordinary Stata data sets. If you need to know the number of missing values in the whole matrix, a row, or a column, use missing. rowmissing or colmissing respectively. missing returns a scalar, rowmissing returns a column vector (one value for each row in the matrix), and colmissing returns a row vector (one value for each column in the matrix). y(1,2,.)(4. 6)(7,8,.) missing(y) rowmissing (y) colmissing(y) To get the number of non-missing values, using nonmissing. rownonmissing. or colnonmissing . Descriptive Statistics Mata has a set of functions for calculating descriptive statistics, though by design its not as rich as Statas. In their simplest and most commonly used forms, all these functions take a single matrix as their argument. Sums may be stretching the definition of quotdescriptive statisticquot but they are very useful. There are three main sum functions: sum. rowsum. and colsum. sum adds up the whole matrix, returning a single number. rowsum adds up each row, returning a column vector. colsum adds up each column, returning a row vector. sum(x) rowsum(x) colsum(x) max and min simply return the largest or smallest element of the matrix. rowmax and rowmin return a column vector containing the largest or smallest element of each row. Likewise, colmax and colmin return a row vector. You can get the largest and smallest elements with the minmax functions, including minmax. rowminmax. and colminmax. They return both the min and the max in either two columns or, in the case of colminmax. two rows. Sometimes youre more interested in where the min or max is than what it is. If so, check out minindex and maxindex. The mean function returns a row vector containing the column means of the matrix. If you need row means, youll need to construct them yourself: You can also get the variance matrix of your matrix with variance, and the correlation matrix with correlation. Matrix Characteristics Mata has functions for finding the most common matrix characteristics. diagonal returns the principal diagonal of a matrix as a row vector. trace returns the sum of the diagonal elements. det returns the determinant (with some round-off error). rank returns the rank of the matrix. As a general rule, using rank to check that a matrix is full rank because a subsequent calculation requires it is redundant--better to let the subsequent calculation fail and handle the failure. Also, when determining the rank of a matrix on a computer a certain tolerance is required for round-off error. Different functions can use different tolerances, so they may disagree with the rank function. Solvers, Inverters and Decomposition Matrix solvers are functions designed to solve the equation AXB for X. Since inverting a matrix A can be done by solving the equation AXI, inverters and solvers are closely related. In addition, the solvers and inverters generally work by doing some sort of decomposition, and the decomposition methods can also be accessed directly. Thus there are several families of three related functions. Which family youll choose depends on the properties of your matrix. Well focus on Cholesky methods, but the others work in a very similar way. The Cholesky Decomposition decomposes a symmetric, positive definite matrix into a lower triangular matrix times its transpose. The results can be used to solve matrix equations and find inverses much more quickly than more general methods. To get an example matrix we can work with, we can take advantage of the fact that if x is of full rank, xx is symmetric and positive definite--and random matrices are all but certain to be full rank. So: The cholesky function takes one argument, a matrix, and returns a lower triangular matrix which is its Cholesky Decomposition. To verify that it works, note that is the same as a. To illustrate solving a matrix equation, we need a right-hand side. The cholsolve function takes two arguments, both matrices. It them sets up and solves the equation AXB where A is the first matrix and B is the second, returning X. To verify that it worked, note that The cholinv function takes one argument, a matrix, and returns its inverse: Again, to verify it worked try The result should be an identity matrix. Youll notice that round-off error makes some of the zeroes not quite zeroes, but its as close as you can get using a computer. If your matrix is square but not symmetric, LU Decomposition can do similar things (though its slower than Cholesky). The lud function is equivalent to cholesky. but more complex because it has to give back three results. Thus the matrices to store the results have to be passed in, similar to stview . LU Decomposition breaks a matrix into a lower triangular matrix L, an upper triangular matrix U, and a permutation matrix P. But Mata, instead of using a matrix P, gives a column vector p which can be used with subscripting to do the same thing. Take look at L. U. and p. To verify that it worked, see that is a. Note how were using subscripts to pull rows from a result, not an existing matrix, and yet it works just fine. lusolve and luinv are much simpler--in fact the usage is identical to cholsolv and cholinv. Try Similar functions exist for QR decomposition ( qrd. qrsolve. qrinv ). Singular value decomposition has svd and svsolve. but the related inverter is pinv (which returns the Moore-Penrose pseudoinverse). invsym. for inverting symmetric matrices, has no related decomposition or solver functions. It is, however, what Stata suggests for linear regression. Example: Linear Regression Youre now prepared to do the most common matrix manipulation of all, at least at the SSCC. Since we have the automobile data set loaded, lets regress price on mpg, rep78, foreign and weight to see which characteristics American consumers were willing to pay for in 1978. One complication is that rep78 is missing for some observations, so youll need to drop them from your regression. Of course you could just drop them from the data set entirely, but lets assume that you want to keep them for later use. The first step is to mark the observations you can actually use. Exit Mata by typing end. then create a new variable touse which is one if all the variables are non-missing and zero otherwise. gen touse(price. amp mpg. amp rep78. amp weight. amp foreign.) Of course in reality the only variable that is ever missing is rep78. but well pretend we didnt know that ahead of time. If you wanted to run a regression on a subpopulation (say, just the foreign cars) you could add a condition to mark the subsample too. Now go back into Mata by typing mata. Next make x a view onto all the independant variables and y a view onto the dependant variable. touse is the selection variable for both views: observations will only be included if it is equal to one. stview(x0. (quotmpgquot, quotrep78quot, quotweightquot, quotforeignquot), quottousequot) stview(y0. (quotpricequot), quottousequot) To include a constant term in the regression you need to add a column of ones to x. Use the J function to create it, then add it to x with the comma (column join) operator. Now you can find the betas: Of course they dont mean anything without standard errors. Start by finding the residuals: Then the variance-covariance matrix is The standard errors for each beta can be extracted using the diagonal function, along with sqrt. which takes the (element by element) square root. The t-statistic is the beta divided by the standard error, but this is an element by element division so you need to use the colon operator. To find the p-values requires the ttail function, which takes as arguments the degrees of freedom and the t-statistic and returns the probability. It is a single-tailed test however, so you need to multiply by two. To put your results together in a readable form, try: Now exit Mata again, and check your results against reg price mpg rep78 weight foreign They should be identical. In regular Stata, if is almost always used to define which observations a command should act on. Its the equivalent to SQLs where clause. In Mata, if is only used to control program flow. (Though Stata can use if in this way as well--see the appropriate section of Programming in Stata .) The most basic form of if is simply if ( condition ) statement If condition is true, then statement is executed. Otherwise it is skipped entirely. Note that the condition must be in parentheses. If you want to do more than one thing if the condition is true, use the following syntax: if ( condition ) statements You can also use else to specify things that should happen if the condition is not true. Thus you can create fairly elaborate structures: if ( condition1 ) statements1 else if ( condition2 ) statements2 else statements3 Keep in mind that each condition has a single result, either true or false. For example, If x is a matrix you cant write if (xgt5) and then list things you want done for those elements of x which are greater than 5. You can write if (x1,1gt5) followed by if (x1,2gt5) etc. but of course the easy way to do that is using a loop. Mata has while. do - while. and for loops available (plus goto for easier conversion of FORTRAN code, but we dont want to endorse spaghetti logic). while looks very similar to if: while ( condition ) statements The difference is that the statements will be executed over and over as long as the condition is true. Thus your first concern should be to make sure that at some point the condition will become false, or the loop will run forever. Note that x is shorthand for xx1. Even though we said xlt5, the final value of x is six. Thats because the loop only decides to end when x becomes six. You can also put a while loop with a single statement in a single line. This loop is perfectly legal, but it didnt do anything. The reason is that the condition started out false, so the loop never executed at all. Sometimes you need to make sure that a loop runs at least once, and thats a job for do-while. A do-while loop starts with do and ends with the while condition. The statements are always executed at least once. If the condition is true, the loop starts over again from the top. Note that x is increased to seven even though it started out greater than five. One typical use for do-while loops is to do something until it converges: do complex mathematical stuff while (abs(newvalue-oldvalue)gttolerance) But unless youre absolutely certain your process will actually converge, youd better put in an escape clause that tells it to stop after a while whether it converges or not: do complex mathematical stuff while (abs(newValue-oldValue)gttolerance amp iterationltmaxIterations) Recall our first while loop: This is such a common structure that programmers wanted a quicker way to construct it. The answer was for loops. The for loop equivalent to this while loop is Note the three components: an initialization step, a rule for when the loop should end, and some sort of progression towards that ending. Strictly speaking you can skip the initialization and the progression--just leave the semi-colons as placeholders. All this really means though is that youre promising to take care of those steps yourself. In particular x must already be defined and you need to make sure the loop will in fact end. By far the most common use of for loops is to loop over the elements of a matrix. Writing Your Own Functions Mata allows you to write your own functions--in fact many of the standard functions weve used are written in Mata. As youve seen, calling a function is a matter of typing the function name and then giving a list of arguments in parentheses. Defining a function follows the same structure: first the word function to tell Mata what youre doing, then a name, and then a list of arguments in parentheses. The body of the function follows in curly brackets. If you want your function to return a result, one of the statements in the body needs to be return. followed by the thing to return in parentheses. function myfunction(x, y) statements return(z) As an example, consider the following (not terribly useful) function. function doubleAndSum(x) xx2 return(sum(x)) This function takes a matrix, multiplies it by the scalar two, and returns the sum of all the elements in the matrix. To test it, try the following: mI(3) doubleAndSum(m) m Note that you passed in a matrix called m even though the function calls it x. Thats fine: the doubleAndSum function refers to whatever it is given as x. In fact the input doesnt even have to have a name. In the first case, the argument passed in is the result of the I function. In the second, it is a row vector defined on the spot. On the other hand, in these cases we cant see how the input matrix was doubled as they arent stored anywhere. Function arguments in Mata are quotpassed by reference. quot If a function changes one of the arguments it is given, that change persists even after the function is completed. Example: Loops and Functions Our next example comes from basic physics, but the real point is using loops and functions to get useful results. The classic equation for the motion of a body under uniform acceleration is simply Depending on the level of mathematics used in your last physics course, you may or may not have worked with that as a vector equation, where x, x0,v0 and a are vectors with one number for each dimension. The vector component makes this a good problem for Mata. Lets track and plot the movement of a falling object for ten seconds. Begin by defining a function x which takes x0,v0,a and t as arguments and returns the position of the body at time t. This is a good point to pause and test what weve done so far before moving on. Try: This represents a body just moving at 10 meterssecond (not that Mata cares about the units) in the positive x direction, so it will be easy to tell if your function works properly or not. should give 100,0,0. But that doesnt guarantee our acceleration term is right, so try This should give 0,0,50. Now well set up the actual values we want to examine: This is an object starting 500 meters up, moving to the right at 100 meters per second, and falling under normal earth gravity (about 9.8 meters per second squared). Note how we suddenly switched from three dimensions to two. Your function wont care in the slightest since theyre all still matrices, but its a lot easier to plot on a two dimensional graph. Now you need somewhere to put the results. Mata doesnt do graphs, so youll have to use Stata to plot them. But first we have to think about what the results will be. Your function provides a snapshot of the object at any given time, so well take a thousand snapshots spread across the ten second span. Each snapshot will have two numbers, an x coordinate and a y coordinate, so those will be your variables (though to Mata theyre just column one and column two of the x row vector). Get out of Mata, then use standard Stata commands to set up the observations and variables youll need. Now get back into Mata, and set up a view of these variables. Call it r (as in results): Now youre ready to loop over your 1000 snapshots and get the results of the x function for each one: Note how the time for each snapshot, i100, spreads them evenly across 10 seconds as i goes from 1 to 1000. Finally exit Mata again, and create the graph. end scatter y x Its the classic parabola of projectile motion as you no doubt expected, but of course the real point was to practice using functions and loops to generate and work with data. As soon as we defined the x() function, Mata compiled it into quotobject code. quot This is not quite the same as machine-language code that can be run all by itself. But it is something Mata can understand and run very quickly. If you were planning to use this function in the future you could save the object code. Then future programs wouldnt need to spend time compiling it. If this is something youre interested in, see the mlib and mata mosave commands. This example is contained in ex1.do. A pointer is a variable which contains the memory address of another variable or matrix. Thus it quotpointsquot to that other variable. In principle a pointer is just a number, but youll never work with the number directly. Instead, youll use two operators, amp and . Computer scientists call these the quotreferencequot and quotdereferencequot operators, but I like to think of them as quotthe address ofquot and quotthe thing at. quot Consider the following: First we define a matrix x so we have something to work with. Then p is defined as quotthe address of x. quot Thus p or quotthe thing at p quot is just another name for x. You can use subscripts with p just like you would with x. but note how you have to put p in parenthesis first. (p)2,2 means quotfind the thing at the address contained in p and get the value at row two, column two. quot p2,2 would mean quotget the value at row two, column two of p. and then find the thing at that addressquot which wont work because p is a scalar. Note that the matrix you are pointing to doesnt need to have a name. For example: makes p point to a 5x5 matrix of zeroes (since thats what J returns) even though theres no direct name for that matrix. Its only accessible as p. One use for pointers is to construct data structures Mata doesnt handle automatically. For example, you can construct a three dimensional matrix by making a two dimensional matrix of pointers, each of which points to a column vector. The first step is to define the matrix that will contain the pointers. Matrices cant switch between containing numbers and containing pointers, so you need to make sure that the matrix is defined as containing pointers. On the other hand, we dont have any actual pointers to store yet. Thus well set the initial values of the matrix to NULL. a special pointer that doesnt point to anything. Now loop over all the elements of x, and make each one a pointer to a new (and unique) column vector. To work with an element i, j,k of your three dimensional matrix youd use the following: Yes, the parentheses are essential. Its rather awkward though, so if you were going to work with such matrices a lot consider defining the following functions: function put(val, x,i, j,k) Usage: value to put, matrix to put it in, i, j, k to put it at. ((xi, j))k,1val function get(x, i,j, k) Usage: matrix to get from, i, j, k of value to get. return(((xi, j))k,1) Then you can do things like: The fact that you cant mix pointers and regular data within a matrix does limit your flexibility. You cant, for example, have a matrix of individual data including pointers to other data relevant to the individual. You can, however, have two parallel matrices, one containing numbers and the other containing pointers. If row i represents the same individual in both matrices, you can pull information from either or both as needed. Its also possible to create a pointer to a function. Given your existing function doubleAndSum() try: Note how Mata distinguishes between x() the function and x the variable by the parentheses, even though youre not passing in any arguments when you define a pointer. The main reason youd want to create a pointer to a function is so that you can use that pointer as the argument of a function. For example, Matas optimizer functions have you pass in a pointer to the function which is to be optimized. The Mata Optimizer Many statistical operations involve maximizing or minimizing some quantity--maximum likelihood estimation being the obvious example. Mata includes an optimizer for these operations. Matas optimizer is actually a family of functions which define and then solve an optimization problem. Evaluator functions The first function must be written by you: the function to be maximized or minimized. This function can do whatever you want, it may be very complex or very simple, but it must accept a certain set of arguments and return the proper result in order for the optimizer to use it. You can name the arguments whatever you like, but there must be the right number and each must have the proper meaning. Optimization problems are described using a variety of notations, but if we consider the problem of maximizing yf(x), the Mata version of f() must take the following arguments: a number indicating whether the function is supposed to calculate (0) just f(x), (1) yf(x) and f(x) or (2) f(x), f(x) and f(x) x (the thing that changes as the optimizer looks for the max) y (where f(x) will be stored) A variable to store f(x) if calculated A variable to store f(x) if calculated (often H since it is the hessian in multivariate problems) If you can find an analytic solution for f(x) and f(x) and code them in, Matas optimizer will be much faster and more accurate. This is often impractical though, and Mata is perfectly willing to find numeric approximations to the derivatives it needs. Note, however, that even if your function never calculates derivatives it must still accept variables where they can be stored. So lets try a very simple function: y-x4. If youre willing to let Mata find all the derivatives for you, you can code this as the following: Note that todo (the number telling the function whether to calculate derivatives or not), g. and H are completely unused, but must still be accepted. Note also that we could change all the names. We could call x Fred and y George as long as Georgef(Fred). If were not quite so lazy we can also code the derivatives for this function quite easily: In this case, both x and y were scalars, but youre not limited to scalars. Consider y-x14 - x24 The two xs are stored in a row vector x, so x1 is x1 and x2 is x2. Making sure the optimizer sends in the right size of x is one of the steps in setting it up. In many cases the quantity youll want to maximize will be the sum of a column. For example, in maximum likelihood you will probably create a column where each row gives an observations contribution to the likelihood function. Matas optimizer will do this automatically with the proper settings, so the previous function could be recast as: Note how the function had to define y as a column vector of the proper size--otherwise it is a scalar. In statistical applications the quantity to be maximized will depend not just on parameters that can vary (x in our problems thus far) but on data that do not vary. Matas optimizer can be set up to pass up to nine additional arguments to your evaluator function, which can contain the data. They go after the first two arguments (and before the final three). This calls for a change of variable names. Consider maximizing sf(b). Well now use x for the data matrix. Then the function definition would be: function f(todo, b, x, s, g, H) x can contain both the independent and dependant variables, but if its easier to work with a separate matrix y, then the definition becomes: function f(todo, b, x, y, s, g, H) Well do an example using this kind of evaluator shortly. Setting Up and Running an Optimization Problem Once youve got your evaluator function defined, youre ready to set up the optimization problem. The first step is to call the optimizeinit function. optimizeinit takes no arguments and returns a variable containing a description of your optimization problem. Youll never look at this description, but you will pass it in to all the other optimization functions. Next tell it where to find the evaluator: The first argument is the problem description, and the second is a pointer to the evaluator function you already defined. Now give it a starting value for x--remember the f() function is in the form yf(x). Of course the correct answer is zero, but we want it to do some work Now youre ready to actually run the optimizer: This returns the value of x which maximizes f(x). You may want to store this in a variable: If we want to use the g(x) function instead, theres one additional step. Recall that in g(x) we coded the first and second derivatives ourselves so Mata doesnt have to approximate them. Mata refers to this as a quotd2quot evaluator. A quotd1quot evaluator codes just the first derivative, and a quotd0quot evaluator codes no derivatives at all (the f(x) function is a d0 evaluator). Mata will assume functions are d0 unless we say otherwise, so you need to add: Note that the optimizer doesnt care what order all the initialization functions are called in, as long as theyre before the actual optimize(). What about h(x1, x2) Its identical to f(x), except that we need to set an initial value for both variables: In doing so we also tell Mata that future xs must have two columns. Finally, i(x1,x2), where the function to be maximized is the column sum of y, is what Mata calls a quotv0quot evaluator. The quotvquot is for vector, and the quot0quot again means that we didnt code any derivatives. Thus we need To see the complete code to run the optimizer with each evaluator, see the the last parts of mataclass. do. There is one setup function we havent needed to call but you should know: changes the problem from maximizing the function (the default) to minimizing it. Example: Ranking Teams As a final, extended example, consider a problem familiar to any sports fan: determining how good a team is based on its wonloss record. Well assume that a team can be characterized by a single quotstrengthquot variable s. If team i plays team j, well assume that the probability of team i winning is given by exp(si-sj)(1exp(si-sj)), better known to Stata as invlogit(si-sj). Then, given a record of games played and who won, we can find a set of values for s that maximizes the probability of the given outcome. Well do a Monte Carlo study by first creating data which fits our assumptions, and then seeing how well the method works. Creating the Data The first step is to create the data. This is an exercise in matrix manipulation, so if you want to focus on the optimization part of the problem feel free to skip ahead. On the other hand, most readers will benefit from some practice in this area. First create a row vector str containing the real strengths of each team. For simplicity, use the uniform function, giving strengths distributed uniform(0,1). For our example well make 50 teams: Note that the column number within the str vector acts as a sort of team ID. Next we need a way to keep track of who played who. Well create a two-column matrix, where each row is a game and the two columns will contain the IDs of the two teams who played in that game. For brevity well call the team in column one the quothomequot team and the team in column two the quotvisitingquot team. Well assume that each team plays 20 games, 10 as the home team and 10 as the visiting team. Begin by creating a column vector teams containing the 50 teams using the range operator: Now create a column vector season which is just ten copies of teams stacked on top of each other: seasonteams for(i1ilt10i) seasonseasonteams This represents the home teams. Next assign the visiting teams by taking the same vector, putting it in a random order, and column joining it to the original: The only trouble is, its entirely possible for a team to be randomly assigned to play itself. This wouldnt really bother our estimator, but it does offend any claims that this represents the real world. More importantly, fixing it is good practice. Create a column vector same with the same number of rows as season which contains a 1 if the home and visiting teams are the same and a 0 if they are not: If a game has the a team playing itself, we will swap the visiting team with the visiting team of a randomly chosen game. Since its possible we might get the same team yet again, well keep checking and swapping until there are no more games between the same team. Heres the code: while (max(same)1) for(i1 iltrows(season) i) if (samei) swaptrunc(uniform(1,1)rows(season))1 tempseasonswap,2 seasonswap,2seasoni,2 seasoni,2temp same(season.,1:season.,2) Note how max(same) will be zero if there are no longer any games where the home and visiting teams are the same, so thats how we know when were done. We then loop over the rows, stopping to change those where samei is one (or true). In those cases, we pick a random row and swap visiting teams with it, using a temp variable to store its visiting teams ID as we do. We then recalculate same based on the new version of season before the while condition is reevaluated. Now we need to decide who won each game. Well create a column vector winner, which will contain a 1 if the home team won and a zero if the visiting team won. winnerJ(rows(season),1,.) for(i1 iltrows(season) i) winneriuniform(1,1):ltinvlogit(strseasoni,1-strseasoni,2) Note how indexing is used to pull up the strength ( str ) of the appropriate team--well be doing that a lot. The Maximum Likelihood Estimator Now were ready to construct the (log) likelihood function to be maximized. Well start with a version thats easy to understand, and try to make it efficient later. function llf(todo, strhat, season, winner, llf, g,H) llfJ(rows(season),1,.) for(i1iltrows(season)i) if (winneri) llfilog(invlogit(strhatseasoni,1-strhatseasoni,2)) else llfilog(invlogit(strhatseasoni,2-strhatseasoni,1)) This will be a v0 evaluator which takes season and winner as additional arguments. The estimated strengths are stored in strhat, and the column of log likelihoods (which will be summed automatically by virtue of being v0) is stored in llf . We have two possible outcomes, and the formula for finding the log likelihood is different in each outcome. For now well handle the two possibilities with an ifelse structure, but there are more efficient ways. Now to set up the optimization problem: soptimizeinit() optimizeinitevaluator(s, ampllf()) optimizeinitevaluatortype(s, quotv0quot) strhat0J(1,rows(teams),.5) optimizeinitparams(s, strhat0) optimizeinitargument(s,1,season) optimizeinitargument(s,2,winner) strhat1optimize(s) Most of these youve seen before. Note that strhat0 is the vector of starting values for our estimate of str. Since the actual strengths are distributed uniform(0,1) well start by setting them all to 0.5. What is new is optimizeinitarguments. This is where you tell the optimizer to pass in season and winner to your evaluator. As you see optimizeinitarguments takes three arguments: the optimization problem, the number of the argument youre setting, and what to pass in. Run the code. It will take a while but it should work. Efficiency So how can we make it faster It would be nice if we didnt have to figure out which formula to use for the likelihood. So lets rearrange the data a bit: instead of column one being the quothomequot team and column two the quotvisitingquot team, terms which have no real meaning in our model, lets make column one the winner and column two the loser. Create a new matrix season2 with the new arrangement: season2J(rows(season),2,.) for(i1iltrows(season)i) if (winneri) season2i,.seasoni,. else season2i,.seasoni,(2,1) Of course this loop takes time to run, but it only runs once. Its the evaluator that must be run over and over, so taking a bit more time to set things up so that the evaluator runs faster is well worth it. One general principle when it comes to writing fast Mata code is that matrix operations are faster than loops you write out. Theres no matrix operation that would allow you to look in one matrix for the estimated strength of a team identified in another matrix, but you can take calculating the log and invlogit functions out of the loop. Heres a second and more efficient version of the evaluator function: function llf2(todo, strhat, season, llf, g,H) xJ(rows(season),1,.) for(i1iltrows(season)i) xistrhatseasoni,1-strhatseasoni,2 llflog(invlogit(x)) Note how it doesnt need to have the winner matrix passed in anymore--it expects a version of season ( season2 ) that conveys that information by which team is in column one. Heres the setup needed to run this version: soptimizeinit() optimizeinitevaluator(s, ampllf2()) optimizeinitevaluatortype(s, quotv0quot) strhat0J(1,rows(teams),.5) optimizeinitparams(s, strhat0) optimizeinitargument(s,1,season2) strhat2optimize(s) Youll see that this runs in about half the time of the original. Most of the gain comes from moving the calculation of log and invlogit out of the loop. For those looking for the absolute best performance, consider turning on matastrict ( mata set matastrict on ). Matastrict requires that you declare the names and types of all variables before using them rather than letting Mata choose. Mata has more variable types than most languages, and they can be confusing. On the other hand, declaring your variables can help you avoid errors. More importantly, Matas compiler can use the additional information to create slightly more efficient object code. If you are interested in using matastrict, see the manuals and especially the section on declarations. Constraints One characteristic of this model is that only the difference between teams is identified. You could add 100 or -1,000,000 to all the strengths and the probability of each outcome would remain the same. Thus two different runs on the same data could give very different numbers and both be right. However, if we constrain just one strength to be a given number, then all the strengths are identified. Matas optimizer accepts constraints on the parameters in the form of two matrices C and c. The parameters p are then constrained such that Cpc . Lets constrain the strength of team one to be zero. To implement this, the C matrix needs to be a row vector with a column for each team. It will have a one in the first column and a zero in all other columns, which makes it a unit vector. c will be simply the scalar zero. You then pass in this constraint using the optimizeinitconstraints function. It takes two arguments: the problem s. as usual, and then a matrix which is the row join of C and c. Im not sure why it doesnt just take them as two separate arguments, but its easy to join them. Since youve made no other changes to the problem, you can simply run it again by calling optimize. This version will actually run significantly faster. As an exercise, consider constructing some sort of metric for how well your estimator does. (One easy one would be how often it correctly identifies the best team.) Then vary the number of games per season and see how many it takes to get reasonable accuracy. However, dont do this if you want to continue to take the ranking systems of actual sports seriously. This example (with additional commands for timing each method) is found in ex2.do. Learning More This article has just scratched the surface of whats possible in Mata. Theres obviously much more to learn, and even more to be looked up when you need it. As usual, Stata Corp. has included most of the Mata documentation in the online help. There is one trick though: to get help for Mata you need to type help mata topic rather than just help topic. This is especially important for functions and such that exist in both Mata and Stata. For example, compare the results of the following: help abs help mata abs A couple useful starting places: help mata help mata functions The Mata manuals are available in the CDE Library and the 4218 lab. There are two books, but they should be thought of as two volumes of the same manual. You are also welcome to ask the Help Desk for assistance. Mata is new to us as well, but well try to figure things out together. Last Revised: 10242007

No comments:

Post a Comment