跳到主要內容

R語言翻轉教室-5【01-RBasic-05-Arrays-Matrices】


*建立一個型態為numeric,由1到18的向量。

seq(1,18)

*利用`matrix`這個函數來建立一個矩陣。舉例來說,就可以建立一個6 乘3 的矩陣。 請同學試試看,並把這個矩陣寫入變數x 。

x <- matrix(1:18, 6, 3)

利用attributes(x)可以看到以下結果:

$dim
[1] 6 3

這代表著x有一個名字叫做"dim"的屬性,值是`c(6, 3)`,代表這是一個6 乘3 的矩陣

更高維度的矩陣 matrix(行 ,列,組)

舉例:

matrix(1:18,6,3) 也可以用這樣表示=> array(1:18, c(6,3))

     [,1] [,2] [,3]
[1,]    1    7   13
[2,]    2    8   14
[3,]    3    9   15
[4,]    4   10   16
[5,]    5   11   17
[6,]    6   12   18

dim(x) <- c(3,3,2)

cbind, rbind

cbind(matrix(1:4, 2, 2), matrix(1:4, 2,2))`會將兩個矩陣的行合併,運算之後會變成2 乘 4的矩陣。請同學試試看。

範例:
cbind(matrix(1:4, 2, 2),matrix(1:4, 2,2))

     [,1] [,2] [,3] [,4]
[1,]    1    3    1    3
[2,]    2    4    2    4

rbind(matrix(1:4, 2, 2),matrix(1:4, 2,2))

     [,1] [,2]
[1,]    1    3
[2,]    2    4
[3,]    1    3
[4,]    2    4

在R 中,線性代數運算的底層是透過BLAS等函式庫做運算的,所以效能遠勝過自己用C 寫的線性代數運算。 另外,R 預設的BLAS庫為比較被廣泛驗證過正確性的版本,而非效能比較快版本。 這是因為,R core Team認為正確性比較重要,所以目前是採用比較舊,但是也比較可靠的BLAS庫。

在R 中,要對一個矩陣做轉置,可以用`t`這個函數

我們可以用diag快速建構對角化的矩陣。舉例來說:diag(1, 3)會建立出3 乘3 的單位矩陣。請試試看。

範例:
diag(1,3)

     [,1] [,2] [,3]
[1,]    1    0    0
[2,]    0    1    0
[3,]    0    0    1

最後關卡63卡關

課程筆記參考: R語言翻轉教室

回家作業:連結

留言

這個網誌中的熱門文章

【Quora 翻譯&整理】對於程式初學者嘗試解決問題的好網站推薦

原文出處: What are some suggested websites to solve programming problems for beginners? (2016/5/15) 此篇文章強調的是去參加project的那種網站推薦

第一章 電腦、網際網路與全球資訊網簡介

C++  How to Program 7/E 筆記 第一章 電腦、網際網路與全球資訊網簡介 學習目標 基本軟硬體觀念 物件技術觀念(類別、物件、屬性、行為、封裝、繼承) 程式語言的種類 典型的C++開發環境 業界標準物件導向素模語言——UML 沿革 網際網路、球球資訊網與Web 2.0現象的沿革 在Linux 的GNU C++ 與在Microsoft Visual C++環境中測試C++ 應用程式 *結構化程式設計(structured programming) *物件導向程式設計

【 Intro to Java Programming 】Lesson 1 : Introduction-5 (Algorithms)

This Notes is according to the udacity free course : Intro to Java Programming Lesson 1 : Introduction-5(Algorithms) Key Word : pseudocode Algorithms just like a doing things protocol+condition. Without protocol+condition, you can not make choice or do the decision. So if you want to buy car, you know the car speed and you don't consider the car price or the car condition, so it is your thought, it is the algorithm you buy a car. For computer, we give them the program ===>for them to do algorithm, but now we try to write done in Pseudocode. Pseudocode write in "spoken language" which help us to understand the problem so we can translate them into computer language ==>JAVA Code.org maybe it could help you have fun from learning code