How to change each column of data in a matrix into a comma expression in an elegant and efficient way?
조회 수: 2(최근 30일)
표시 이전 댓글
I want to convert a numeric matrix with multiple columns to a comma expression, especially when the matrix has more columns, using cell type to indirectly convert the comma expression does not look very natural and elegant, I can't find a function in matlab that can convert it perfectly in one step, how can I achieve this? For example, there is the following example.
data = rand(3,5);
numCols = size(data,2);
C = cell(1,numCols);
for i = 1:numCols
C{i} = data(:,i);
end
% then i can get comma expression by C
C{:}
I want to achieve the above operation in one step, for example, I want to directly convert the above matrix A to table type, each column is a matrix, but the following syntax does not support, I have to follow the above syntax loop to assign the value, I feel the code is not elegant enough:
myTableData1 = table(C{:},VariableNames=["var1","var2","var3","var4","var5"])% support a comma expression input!
myTableData2 = table(data,VariableNames=["var1","var2","var3","var4","var5"]) % not support,data should a comma expression!
update:
The above multiple inputs of type table is just an example, for example, there is such a function fun(a,b,c,...) , there are multiple inputs of unknown quantity, how can we quickly convert to comma expression input? (not indirectly through similar cell,struct,sting type operations)
댓글 수: 3
Stephen23
2022년 6월 21일
편집: Stephen23
2022년 6월 21일
"there are multiple inputs of unknown quantity, how can we quickly convert to comma expression input? (not indirectly through similar cell,struct,sting type operations)"
This is not possible, for the reason explained here:
" I can't find a function in matlab that can convert it perfectly in one step"
This is not possible, for the reasons explained here:
Note that even if such a syntax existed it would unlikely make any difference to the existence of any intermediate arrays in memory, i.e. it is unlikely that such a syntax would make your code more efficient. For example, using NUM2CELL splits the array into subarrays, whose handles can then be allocated to variables/cells/fields using a comma-separated list. But your proposed syntactical sugar would still need to split the array into sub arrays before the comma-separated list, yet that is exactly the step that you state you want to avoid.
채택된 답변
추가 답변(0개)
참고 항목
범주
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!