根据另一列将列的元素分配到矩阵中 [英] Distribute elements of column into matrix based on another column

查看:84
本文介绍了根据另一列将列的元素分配到矩阵中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编写执行以下操作的脚本时,我需要帮助:

i need help on writing a script that does the following:

data = [1 1 2; 
        2 1 3; 
        3 3 4; 
        3 3 5; 
        4 3 6]

脚本需要检查第二列中的数字是否重复.下面的草图说明了我要完成的工作:

The script needs to check if a number in the second column is repeated. The sketch below explains what it is I would like to accomplish:

对于第二列中的每个重复值,我想将第三列中与第二列中的每个重复值共享的所有值作为正确列中的条目,如果不重复该值,请说2- ->以4为例,脚本将需要检查数字2是否属于上一层,如果是,那么来自它的任何数字都将属于下一层

For each repeated value in the second column, I'd like to all values in the third column that share each repeated value in the second column as entries in the correct column and if the value is not repeated say the 2--->4 as an example, the script will need to check if number 2 belongs to the previous layer if so whatever numbers comes from it will belong to the next layer

尽管现在是分支编号的步骤,但仍需要对分支进行编号,使其远离根(节点1),如下图所示.仅在对上一层中的所有分支进行编号之后,才开始对一层中的分支进行编号.然而,在进行向后扫描迭代(以计算每个节点的电流)时,应将发束结构视为一个径向的分布式发电系统.脚本如何判断例如节点8和5之间的line7,其中5也是line4的一部分,等等...?任何专家的建议都欢迎

Although, now comes the step of branch numbering, need to number the branches in layers away from the root(node 1) as shown in the pic below. the numbering of branches in one layer starts only after all the branches in the previous layer have been numbered. However, considering the tress structure as a radial electrical distributed generation system, when doing backward sweep iteration(to calculate the current en each node). how can the script tell if for example line7 between nodes 8 and 5 where 5 is also part of line4 etc...? any experts suggestions are welcome

推荐答案

希望我对你正确

data = [1 1 2; 2 1 3; 3 2 4; 4 3 5; 5 3 6; 6 4 7;7 5 8];
mx=max(data(:,3)); %// maximal node index

估计每个节点的层(节点1在层0中):

Estimate the layer of each node (node 1 is in layer 0):

ly = zeros(mx,1); 
for ii=2:mx, 
    ly(ii) = ly( data( data(:,3)==ii, 2 ) )+1; %// get the layer of the parent
end

查看每个节点的层索引(ly):

Looking at the layer index of each node (ly):

0     1     1     2     2     2     3     3

现在,我们根据层将节点划分为列

Now we split the nodes to columns according to layer

for ci=1:max(ly), 
    c{ci} = find(ly==ci); %// put all nodes of layer ci in a cell
end; 

结果矩阵中的行数等于具有最大节点数的层:

Number of rows in resulting matrix equals the layer with maximal number of nodes:

mxc = max(cellfun(@numel,c));

构造结果

res=zeros(mxc,max(ly));
for ci=1:numel(c), 
    res(1:numel(c{ci}),ci)=c{ci}(:);
end;

结果是:

res =

 2     4     7
 3     5     8
 0     6     0

这篇关于根据另一列将列的元素分配到矩阵中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆