Adding valies from a table into a zero matrix
信息
此问题已关闭。 请重新打开它进行编辑或回答。
显示 更早的评论
Hello,
I've created a zero matrix array of the size that I need, and I want to add values from a table to it.
My table is in an excel spreadsheet with three columns. Column 1 denotes the x co-ordinate, column 2 the y co-ordinate, and column 3 the value I want to add. I'm trying to create a loop that will allow me to find the matrix position (x, y) as specified in the table, and then add the third column value to that position only.
I know roughly how to specify positions in each, but not how to then say, 'use the numbers in here to find the position in the array'.
If my matrix is X and table is A, I'm thinking the code needs to be similar to:
i=1
b=A[i,1]
c=A[i,2]
d=A[i,3]
X[b,c] + d
i=i+1
Any help on how to smooth this out would be fantastic as it's been forever since I did anything with tables and matrixes other than pulling values out.
Cheers.
2 个评论
Azzi Abdelmalek
2016-4-16
Make your question clear and brief. Have you a problem to read your Excel file? If not, how your are data are stored? like this ?
M=[1 2 3;
4 5 6;
7 8 9]
Then What is the expected result from M?
Maeve
2016-4-16
编辑:Azzi Abdelmalek
2016-4-16
回答(2 个)
Azzi Abdelmalek
2016-4-16
M=[8 26 240; 39 6 52; 600 530 211]
idx=ismember(M(:,1:2),[8,26],'rows')
out=M(idx,3)
7 个评论
Maeve
2016-4-16
编辑:Azzi Abdelmalek
2016-4-16
Azzi Abdelmalek
2016-4-16
Ok, but you need to explain how to get out from X and A
Maeve
2016-4-16
Azzi Abdelmalek
2016-4-16
We can't provide the criterion at your place. From the example, explain how to get the result, then we can help you to code it
Maeve
2016-4-16
Azzi Abdelmalek
2016-4-16
编辑:Azzi Abdelmalek
2016-4-16
X=zeros(3)
A=[1 2 12; 1 3 8; 2 2 5; 3 3 16]
idx=sub2ind(size(X),A(:,1),A(:,2))
X(idx)=A(:,3)
Maeve
2016-4-16
Guillaume
2016-4-16
A loop is totally overkill for this. There are two simple ways of obtaining your final output:
1. sub2dind which will convert two vectors of row, column coordinates into a vector of linear indices. You then use this linear index to directly assign all the values in one go:
X = zeros(3, 3);
X(sub2ind(size(X), A(:, 1), A(:, 2)) = A(:, 3);
2. Create a sparse matrix with your vectors of coordinates and vector of values and convert to full matrix:
%no need for zero
X = full(sparse(A(:, 1), A(:, 2), A(:, 3), 3, 3));
0 个评论
此问题已关闭。
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!