필터 지우기
필터 지우기

Assign matrix to struct

조회 수: 35 (최근 30일)
Tiki Tiki
Tiki Tiki 2018년 7월 23일
댓글: Tiki Tiki 2018년 7월 25일
Hi everyone
Can you help me for my code?.
I want to assign matrix b to struct g.a at position c.
g(1).a=[1 2 3 4]'
g(2).a=[1 1 3 4]'
g(3).a=[4 3 1 2]'
c=[1 2]
b=[ 3 3 3 3;4 5 4 4]'
My hope output is g.a =
3 4 4
3 5 3
3 4 1
3 4 2
Thank you so much.
  댓글 수: 3
Rik
Rik 2018년 7월 23일
I agree with Jan. If you want to assign vectors to specific fields, you can always use a for-loop, but how you would get your matrix out is unclear to me.
g(1).a=[1 2 3 4]';
g(2).a=[1 1 3 4]';
g(3).a=[4 3 1 2]';
c=[1 2];
b=[ 3 3 3 3;4 5 4 4]';
for n=1:numel(c)
g(c(n)).a=b(:,n);
end
Tiki Tiki
Tiki Tiki 2018년 7월 24일
Thank. but actualy my problem is speed up. so i dont use For here. Can you help me more?

댓글을 달려면 로그인하십시오.

채택된 답변

Guillaume
Guillaume 2018년 7월 23일
편집: Guillaume 2018년 7월 23일
As per jan's comment, g.a means nothing. If you type g.a in the command window, you will get 3 outputs (3 times: ans = ...).
[g.a] will indeed return a matrix, which is the horizontal concatenation of all the outputs of g.a. However, [g.a] does not exist in the structure. I believe that you've misunderstood how structures work if that's what you want.
If you want to replace g(c(i)).a by b(:, i), then the easiest is a loop:
for col = 1:numel(c)
g(c(col)).a = b(:, col);
end
While it can be done without a loop, it's awkward and probably slower:
a = {g.a}; %concatenate all in a cell array
a(c) = num2cell(b, 1); %replace columns determined by c by columns in b
[g.a] = a{:}; %put back into structure
  댓글 수: 4
Jan
Jan 2018년 7월 24일
편집: Jan 2018년 7월 24일
+1. "If you want more speed, then you need to change the way you store your data" - exactly. Speed is not only concerned by the code, but the underlying representation of the data plays an important role.
If g is large, care for a proper pre-allocation. Create e.g. the last field g(max(c)).a at first. If c is sorted, you can run the loop in backward direction:
for col = numel(c):-1:1
But the fastest way would be to keep the matrix b and store only the column indices in the struct array.
Tiki Tiki
Tiki Tiki 2018년 7월 25일
Thank. Can I ask more about GPU?
How can I work this code on GPU? in my case, g.a is big size. and
because I work on each position of g.a, like get g(1).a or g(2).a,
so How do i change data?

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

KL
KL 2018년 7월 23일
probably you mean something like this
g.a(:,1)=[1 2 3 4]';
g.a(:,2)=[1 1 3 4]';
g.a(:,3)=[4 3 1 2]'
c=[1 2]
b=[3 3 3 3;4 5 4 4]'
and then simply use c as indices in a
g.a(:,c) = b
  댓글 수: 1
Tiki Tiki
Tiki Tiki 2018년 7월 24일
Sorry. I dont mean that. because this is a samples in my work. I defined code like that. so i cannot change. Can you help me?

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by