function [cityN,neighbor,neghbor2:neghborN]] = makeneighbor(x,y)
cityN=x;
neighbor=y;
end % this function is false and i just told what is in my mind
例如:
//city1 have 2 neighbors:
[city1,neighbor1,neghbor2]
//but city2 have 4 neighbors:
[city2,neighbor1,neghbor2,neighbor3,neghbor4]
//and city3 have just a neighbor
[city3,neighbor1]
我需要一个flixeble数组,非常感谢...
答案 0 :(得分:1)
不确定这正是您所需要的,但是:
all_cities = {}
all_cities{end+1} = {'New York','Boston', 'Mscow'}
all_cities{end+1} = {'Moscow','Town1', 'St.Petersburg'}
所有城市都是包含所有城市的单元格数组。这个单元阵列的每一个都是单元阵列。每个嵌套的单元格数组都包含主要城市的第一个元素,从第二个元素到最后一个邻居都存储。
说,如果我们谈论纽约,
new_york = all_cities{1};
new_york_neighbors = new_york{2:end};
你还应该检查new_york_neighbors在处理时是否为空。使用函数 isempty()
答案 1 :(得分:1)
我不太确定我是否理解你的问题。要处理不同的数组大小,您可以返回makeneighbor
函数的结构,其中1个字段包含城市名称,第二个字段包含包含所有邻域的单元格数组:
function [] = main_func()
x1 = 'new york';
y1 = {'brooklyn'; 'queens'};
city1 = makeneighbor(x1, y1);
x2 = 'los angeles';
y2 = {'hollywood'; 'downtown'; 'mid-city'; 'bel air'};
city2 = makeneighbor(x2, y2);
% acces to cities
city1.name
city1.neighbor
city2.name
city2.neighbor
end
% function that returns a struct
function city = makeneighbor(x, y)
% generate struct with two fields
city.name = x;
city.neighbor = y;
end
答案 2 :(得分:1)
您可以使用adjacency matrix
cities = {'City1','City2', 'City3', 'City4'}
A =
0 1 0 1 (1 is neighbours with 2 and 4)
1 0 1 0 (2 is neighbours with 1 and 3)
0 1 0 0 (3 is only neighbours with 2)
1 0 0 0 (4 is only neighbours with 4)
(A
应为逻辑类型)
然后,对于任何城市,邻居列表是:
n = strfind('City1',cities);
neighbours = cities(A(n,:));
与自己和邻居的列表将是
self_neighbours = [cities(n),cities(A(n,:))];
邻居数量只是:
num_neighbours = sum(A(n,:));
保持邻居列表与邻居矩阵之类的对象的优点在于它使得执行计算变得更加容易。如果您可以访问Bioinformatics Toolbox,那么您也可以使用它来做各种有用的事情:
b = biograph(A,cities); %makes biograph object
view(b); % shows connection between cities
[dist,path,pred] = shortestpath(b,1,3); % finds path between 1 and 3