开发者

Structure/class in MATLAB?

开发者 https://www.devze.com 2022-12-22 08:13 出处:网络
I have a simple weighted tree with a root, nodes and leafs. Now I want to assign a value to every path from the root to a leaf which will be the sum of all the weights.

I have a simple weighted tree with a root, nodes and leafs. Now I want to assign a value to every path from the root to a leaf which will be the sum of all the weights.

Is there a way of creating a structure with 2 fields: the value and开发者_如何学运维 a vector (which will hold a path) i.e.: (10,[root,node1,node3,node5]) (the length of the path doesn't have to be the same every time!) which I then could store in a vector [path1 path2 path3 ...]?

@Edit: also, I do know there's struct() but I don't really like it, is there any other way to do it?


You should see if a cell array does what you want: {10 [root,node1,node3,node5]}. Read about them here.


I would recommend to store values and path vectors in two separate arrays and combine them into a structure. You can add path length as a separate vector as well. They will be mapped to each other by array index.

leavesN = 20; % number of leaves
treestruct.path = cell(leavesN,1); % to store path vectors
treestruct.sumofweights = zeros(leavesN,1); % to store sum of weights
treestruct.pathlength = zeros(leavesN,1); % to store path length

treestuct.path{i} = [root,node1,node3,node5]; % I suppose those variables are numbers
treestruct.sumofweights(i) = 10;

treestruct.pathlength(i) = numel(treestuct.path{i});

or for the whole tree:

treestruct.pathlength = cellfun(@numel,treestuct.path);
0

精彩评论

暂无评论...
验证码 换一张
取 消