Creating a new matrix basd on the index and value of an existing matrix

1 次查看(过去 30 天)
Hi all,
I am new to matlab and I need your help on this.
I have a m x n matrix and I want to create a new m*n x 3 matrix in which the third column is the value from first matrix and the first two columns are the corresponding index of the value. For example, if the first matrix is [0.001 0.002 0.003 0.004; 0.005 0.006 0.007 0.008], I would like to make a matrix as [1 1 0.001; 1 2 0.002; 1 3 0.003; 1 4 0.004; 2 1 0.005; 2 2 0.006; 2 3 0.007; 2 4 0.008].
So how can I create the second matrix based on the index and value of first matrix?
Thanks in advance.

采纳的回答

Kumar Pallav
Kumar Pallav 2021-9-27
You could try the following code in matlab to get the desired result:
input=[0.001 0.002 0.003 0.004; 0.005 0.006 0.007 0.008];
[nrows ncols]=size(input); %stores the number of rows and columns in input
values=[]; %output matrix
for r=1:nrows
for c=1:ncols
values=[values;r c input(r,c)];% keep appending [r,c,input] to new columns
end
end
disp(values); %display the output
Hope this helps!

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2020a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by