create a new matrix with elements from different sized matrices
7 次查看(过去 30 天)
显示 更早的评论
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!
0 个评论
回答(2 个)
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);
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));
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!