Re: [討論] structure array 初始化大小

看板MATLAB作者 (天)時間9年前 (2015/12/25 14:42), 9年前編輯推噓2(200)
留言2則, 2人參與, 最新討論串2/2 (看更多)
※ 引述《qazzzzz (:D)》之銘言: : 第一次在這發言,請多多指教...>< : 我是想要建一個 structure array, : 而且想要一開始就設定好他有多大, : 可是看到網路上的範例都是依序把資料加上去, : 雖然這樣也是可以寫得出來啦... : 可是就覺得不太習慣, : 覺得在一開始 create variable 的時候就定義好它大小會比較舒服...>< : 例如,我已經知道我有 100 個學生, : 每個學生都有一個名字、和許多個 email (每個學生有不同數目的 email) : 目前都是用 for loop 寫: : for i = 1 : 100 : student(i).name = '他的名字'; : student(i).email = [email1 email2 ...] : end : 想問問大家有沒有可以在一開始定義 student 是 100 個的寫法? : 謝謝大家>< 回一下舊文,最近發現struct其實可以當成array處理 也可以用arrayfun處理struct array 更重要的事情是,initialize的事情也迎刃而解了,用repmat即可 student = repmat(struct('name', [], 'email', []), 100, 1) 這種應用,像是plot時,回傳的是struct也可以這樣做~~ 最近遇到,順便分享一下 arrayfun + struct應用: ex: 1. 取得每一個struct的內容 (字串可以變成cell,數字可為array) arrayfun(@(x) x.name, dir(), 'uni', false) % 得到當前目錄下全部檔案名稱(以cell儲存),ls是字串,而且在mac跟windows行為不同 arrayfun(@(x) x.bytes, dir()) 2. 透過struct array去對每一個struct的資料做處理 datas = repmat(struct('x', [], 'y', []), 100, 1); for i = 1:100 numData = randsample(10:100, 1); datas(i).x = randn(numData, 1); datas(i).y = 1 + datas(i).x * 2 + randn(numData, 1); end lmModels = arrayfun(@(d) fitlm(d.y, d.x), datas, 'uni', false); -- R資料整理套件系列文: magrittr #1LhSWhpH (R_Language) http://tinyurl.com/1LhSWhpH data.table #1LhW7Tvj (R_Language) http://tinyurl.com/1LhW7Tvj dplyr(上) #1LhpJCfB (R_Language) http://tinyurl.com/1LhpJCfB dplyr(下) #1Lhw8b-s (R_Language) tidyr #1Liqls1R (R_Language) http://tinyurl.com/1Liqls1R -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.109.74.87 ※ 文章網址: https://www.ptt.cc/bbs/MATLAB/M.1451025763.A.697.html ※ 編輯: celestialgod (140.109.74.87), 12/25/2015 16:53:47

12/27 14:24, , 1F
推薦這篇文章
12/27 14:24, 1F

01/19 20:09, , 2F
推薦這篇文章
01/19 20:09, 2F
文章代碼(AID): #1MVELZQN (MATLAB)
討論串 (同標題文章)
文章代碼(AID): #1MVELZQN (MATLAB)