Azzera filtri
Azzera filtri

How to assign parts of one structure to another efficiently?

4 visualizzazioni (ultimi 30 giorni)
I have a structure, 'D', which contains 'name'. I would like to assign certain parts of this struct to another struct in an efficient manner. What I have now (which works) is the following:
j = 0;
for i = 1:length(D)
if ( m_u(i) ~= 0 )
j = j + 1;
temp(j).name = D(i).name;
end
end
In this code, the contents of 'D.name' are assigned to 'temp.name' if a vector component is not zero. Is there a more efficient way to do this?

Risposta accettata

Sean de Wolski
Sean de Wolski il 19 Giu 2014
% Sample struct
x = struct('name',cellstr(('A':'I').'))
% sample index (your mu_i)
idx = rand(9,1)>0.5
% extract
[y(1:nnz(idx)).name] = deal(x(idx).name)
  1 Commento
Joshua
Joshua il 20 Giu 2014
Thank you very much, Sean. My code ends up being:
[temp(1:nnz(m_u)).name] = deal(D(m_u~=0).name);
This is an order of magnitude faster than the way I was doing this (~0.5 seconds to ~0.07 seconds!).

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Data Type Conversion in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by