Saving and appending for loop results from every run
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
LeoAiE
el 30 de Ag. de 2021
Comentada: LeoAiE
el 31 de Ag. de 2021
Hi everyone,
I have a dataset with countries and lat/lon columns. I want to measure the distance between the countries. I used the distance function from the mapping toolbox and a for loop to get every single country.
I’m struggling with saving the results from the for loop. I’m overwriting my results. I want to save every run from the for loop as a single column, basically append the results from every run. Does anyone have an efficient/better way to save the results? I would really appreciate your help in advance. I attached the data example and my code
format long g
Data = readtable('Test.xlsx');
for i=1:Data.lat
Distance = deg2sm(distance([Data.lat(i) Data.lon(i)], [Data.lat(1:end) Data.lon(1:end)]));
Data.Distance = Distance
end
2 comentarios
DGM
el 30 de Ag. de 2021
Editada: DGM
el 30 de Ag. de 2021
You appear to be measuring the distance from each point to all other points. The result won't fit in one column and won't be meaningfully aligned with the corresponding rows.
For example, let's assume you have 10 points. The way you're doing this, you'll have 10x10 = 100 distances. Of course, a lot of those distances will be redundant. There would only be 10!/2!(10-2)! = 45 unique distances. If your table is 10 rows long, where would you put 45 entries?
In the first case, you could add 10 distance columns to the table, each one listing the distance from one country to each country in the table. Whether you want to add a bunch of columns is up to you. Either way, it's not going to meaningfully fit in one column with the existing table length.
Respuesta aceptada
Chunru
el 31 de Ag. de 2021
If you want to attach the distance to the Data table you have read, then you can attach the distance vector for each country as follows.
format long g
Data = readtable('Test.xlsx');
for i=1:length(Data.lat)
Distance = deg2sm(distance([Data.lat(i) Data.lon(i)], [Data.lat(1:end) Data.lon(1:end)]));
Data.Distance{i} = Distance;
end
Data
If you want to form a tall vector of distances, or a paired distance matrix you can do the following:
d = [];
for i=1:length(Data.lat)
Distance = deg2sm(distance([Data.lat(i) Data.lon(i)], [Data.lat(1:end) Data.lon(1:end)]));
d = [d; Distance]; % tall vector
%d = [d Distance]; % matrix
end
d
Más respuestas (0)
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!