MATLAB Answers

create a new matrix with elements from different sized matrices

25 ビュー (過去 30 日間)
Sumedh Kulkarni
Sumedh Kulkarni 2018 年 1 月 26 日
編集済み: Sumedh Kulkarni 2018 年 2 月 1 日
The aim is to create a matrix (C_n) from two different matrices (M) and (t_e1) using a equality condition. I am trying to use the following code to do this. However,it gives me output as a matrix with zeros.
C_n=zeros(length(M),length(int));
for i= 1:length(int) %%length(int)=96
for j=1:length(M) %%length(M)=300
if M(j,i)==t_e1(j,1) %%t_e1 is of size 300*2 and M is 300*96
C_n(j,i)=t_e1(j,2); %%Want to check each element of M that equals (j,1)th element of t_e1
%%if true, replace each element of C_n by (j,2)th element of t_e1
end
end
end
What am I doing wrong in the above code?? Also, is there a better way to do get the required output (not using loops)?
Thank you!

回答 (2 件)

Youssef  Khmou
Youssef Khmou 2018 年 1 月 26 日
編集済み: Walter Roberson 2018 年 1 月 26 日
By computing the difference between the two matrices A and B, find the indexes of the entries that equal zero and replace the entries of matrix C with the inputs of the indexes:
example:
A=round(100*rand(4));
B=round(100*rand(4));
T=A-B;
C=zeros(size(A));
[a,b]=find(T==0);
C(a,b)=A(a,b);
  1 件のコメント
Sumedh Kulkarni
Sumedh Kulkarni 2018 年 1 月 26 日
I guess for this solution, matrix dimensions must be same. But in my case, they are not. One is 300*96 and the other is 300*2. I can`t compute difference between them. Also, I don`t want to find elements that equal 0, but the elements that are equal to other matrix`s 1st column.

サインインしてコメントする。


Domanic
Domanic 2018 年 1 月 26 日
編集済み: Domanic 2018 年 1 月 26 日
I think the original code you had was correct, Sumedh. A minimum working example would be helpful, though. Try the following, which computes your loops on one line using logical vectors.
%%Set up example matrices
int = randi([0 3],[96 1]);
M=randi([0 3],[300 96]);
t_e1 = randi([0 3],[300, 2]);
%%Compute C_n
C_n = t_e1(:,2).*(M==t_e1(:,1));
  1 件のコメント
Sumedh Kulkarni
Sumedh Kulkarni 2018 年 2 月 1 日
Dominac, this doesnt work either. I tried to use the example you provided, which works quite well. But for me, i think the elements of Matrix M have same values in some columns. Maybe that`s the reason? It looks something like this:
9 12 20 20 39
10 13 23 36 94
12 20 36 39 124
13 23 39 49 200
20 36 49 94 226
23 39 57 106 275
24 49 94 110 0
36 57 106 124 0
37 88 110 137 0
39 94 124 200 0
49 102 137 201 0
57 106 141 226 0
63 110 200 275 0
75 114 201 0 0
and t_e1 looks like this:
1 92
2 91
3 29
4 93
5 92
6 28
7 68
8 93
9 95
10 96
11 52
12 96
13 96
14 82
15 85
Basically, M(1,1) is t_e1(9,1) and I want element corresponding to t_e(9,1), which is t_e1(9,2) in the new matrix. This needs to be done for each element in matrix M.

サインインしてコメントする。

Community Treasure Hunt

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

Start Hunting!

Translated by