how to create cell array using matrix data?
11 次查看(过去 30 天)
显示 更早的评论
Hello everyone,
I have a data matrix (Data = 4x5x3) showing data in 3months
For example, data in january month
5 8 9 3 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
I want to create data cell with number of row(4) and column(5)
The final output will be
row column data
1 1 1x3
1 2 1x3
1 3 1x3
1 4 1x3
1 5 1x3
2 1 1x3
2 2 1x3
.
.
.
Thanks.
4 个评论
回答(2 个)
Fangjun Jiang
2021-12-17
编辑:Fangjun Jiang
2021-12-17
I think you want to convert 4x5x3 matrix data into 4x5 cell, each cell is a 1x3 matrix data. There is a way to do it but I doublt it will bring you any benefit. Whatever you want to do with the cells, it can be achieved with the original matrix data.
If you want to convert it only for the purpose of interfacing with others, here is how to do it.
Data=rand(4,5,3)
NewData=num2cell(Data,3)
to verify
a1=Data(1,1,:)
b1=NewData{1,1}
To further achieve the format you want
Out=cellfun(@squeeze,NewData,'UniformOutput',false)
Out{1,1}
Voss
2021-12-23
If you need to know the row and column in order to assign to the corresponding element in an output matrix, then there is no need to convert the data to a cell array and also keep track of rows and columns. Just call the function in loops and assign the result:
Data = randn(4,5,3);
display(Data);
[nr,nc,~] = size(Data);
Dom = zeros(nr,nc);
for i = 1:nr
for j = 1:nc
Dom(i,j) = dominance(reshape(Data(i,j,:),[1 3]));
end
end
display(Dom);
But if you really want the rows and columns, you can do this:
Data = randn(4,5,3);
[nr,nc,~] = size(Data);
rows = repelem(1:nr,nc);
cols = repmat(1:nc,[1 nr]);
display([rows(:) cols(:)]);
(dominance function defined here so the code will run. You would use your own.)
% use your own dominance function here
function out = dominance(in)
out = in(2);
end
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!