Combining two arrays question

3 visualizaciones (últimos 30 días)
bio lim
bio lim el 25 de Mayo de 2015
Comentada: bio lim el 25 de Mayo de 2015
Hello. I have a structure array 'data', and I am trying to define a new variable called 'loc'. The problem I am encountering is that I want to get for example, when I write something like loc(1) in the command window, I get [data(1).Lat data(1).Lng].
The following is the code I am using.
for n = 1 : length(data)
if ~isempty(data(n).Lat & data(n).Lng)
loc(n) = [data(n).Lat data(n).Lng];
end
end
I have just started using Matlab and will greatly appreciate your help. Thanks in advance.

Respuesta aceptada

Stephen23
Stephen23 el 25 de Mayo de 2015
Editada: Stephen23 el 25 de Mayo de 2015
You should learn to program without trying on loops for everything: this will be faster and neater code in MATLAB, and is called vectorization. In this case there is no need for any loops or arrayfun calls, just use MATLAB's inbuilt structure accessing syntax:
>> A(3).lat = 1.3;
>> A(3).lng = 0.3;
>> A(2).lat = 1.2;
>> A(2).lng = 0.2;
>> A(1).lat = 1.1;
>> A(1).lng = 0.1;
>> [[A.lat]',[A.lng]']
ans =
1.1 0.1
1.2 0.2
1.3 0.3
Read more here:

Más respuestas (1)

Andrei Bobrov
Andrei Bobrov el 25 de Mayo de 2015
loc1 = permute(struct2cell(data),[3,1,2]);
Loc = arrayfun(@(ii)[loc1{ii,:}],(1:size(loc1,1))','un',0);
  1 comentario
bio lim
bio lim el 25 de Mayo de 2015
I am sorry but I am having a hard time understanding your code. (I am a beginner). Could you explain briefly? Moreover, why there is no variable 'n' involved? Thanks!

Iniciar sesión para comentar.

Categorías

Más información sobre Logical en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by