creating matrix w.r.t. rows number of another matrix
조회 수: 1 (최근 30일)
이전 댓글 표시
data=[1;2;8;9;11;12;19;22;24;26;30];
col_row=[1 2;1 4;1 8;1 11;2 4;2 8;2 11;3 10];
rows number in col_row are always ascending order. I need to store result_i matrix w.r.t. data and rows value of col_row matrix as follows.
result_1=[data(2);data(4);data(8);data(11)];
result_2=[data(4);data(8);data(11)];
result_3=data(10);
rows number in col_row always starts with 1. I need to extract second column values of each repeated numbers (1-2) and single number in col_row matrix and create result_i matrix.
Above data is example, actual data matrix is bigger and the maximum row value of col_row matrix is variable. How can I write a code to store result_i matrix?
댓글 수: 2
James Tursa
2017년 9월 6일
No, you don't want to do this. Creating variables with names like result_1, result_2, result_3 etc is a bad way of programming. It is hard to write downstream code generically to use these variables. The resulting code will be hard to read and hard to debug. Much better would be to use something like cell arrays, e.g. result{1}, result{2}, result{3} etc. These will be easy to use downstream in your code in loops etc.
Stephen23
2017년 9월 7일
"I need to ... and create result_i matrix"
Do not do this. It will make your code complex, slow, buggy, hard to debug, and obfuscated. Read this to know why creating or accessing variable names dynamically is a bad idea:
Indexing is simple, efficient, neat, easy to debug, and easy to understand: you should use indexing with some kind of array: a matrix, or an ND array, or a cell array, or a structure, or a table, or....
채택된 답변
James Tursa
2017년 9월 6일
편집: James Tursa
2017년 9월 6일
E.g., a method using a cell array
u = unique(col_row(:,1));
n = numel(u);
result = cell(max(u),1);
for k=1:n
result{u(k)} = data(col_row(col_row(:,1)==u(k),2));
end
This assumes that all of the "row" numbers are positive integers. If they are not, then one could do this instead
u = unique(col_row(:,1));
n = numel(u);
result = cell(n,1);
for k=1:n
result{k} = data(col_row(col_row(:,1)==u(k),2));
end
댓글 수: 0
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrices and Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!