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