Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add matrix to structure column without using for loop?

Is it possible to add a matrix to a structure 'column' without using a for-loop? For example I have a structure with 3 fields

A.name
A.grade
A.attendance

now A.attendance expects a 1x5 matrix. If I have a 5x5 matrix, can I directly insert it into 5 rows of the structure A? something like

A(1:5).attendance = B

where B is a 5x5 matrix

like image 767
user3079474 Avatar asked Dec 14 '22 10:12

user3079474


2 Answers

If your B is actually a 5 element cell array where each element is a 1-by-5 matrix (actually each element can contain anything), then

[A.attendance] = B{:}

will work. You can convert your 5-by-5 double matrix B to the desired form as follows:

B_cell = mat2cell(B, ones(size(B,1),1),size(B,2))

or skip the temp variable and use deal:

[A.attendance] = deal(mat2cell(B, ones(size(B,1),1),size(B,1)))
like image 86
Dan Avatar answered Feb 16 '23 21:02

Dan


You can convert B to a cell array of its rows,

C = mat2cell(B, ones(size(B,1),1), size(B,2))

and then you can assign as follows

[A(1:size(B,2)).attendance] = C{:};
like image 34
Luis Mendo Avatar answered Feb 16 '23 19:02

Luis Mendo