Help with creating a for loop

2 次查看(过去 30 天)
Christian Basa
Christian Basa 2020-12-12
Can someone help me out with writing a for loop? I'll do my best to explain. So, I need to take the first row of a 20x4096 single and compare it with row 2, then row 3, and then row 4 using cosine similarity where row 1 = x and rows 2 through 4 = y. Then I need to take row 5, compare it with row 6, then row 7, then row 8 and continue that process until I get through all 20 rows. Hopefully that all makes sense. I can provide whatever is needed.

回答(1 个)

James Tursa
James Tursa 2020-12-12
编辑:James Tursa 2020-12-12
You could take this approach:
A = your matrix
AA = A*A'; % all of the dot products between rows (more than you need, actually)
d = sqrt(diag(AA)); % the norms of the rows
AA = AA ./ d; AA = AA ./ d'; % normalize everything, or AA = AA ./ (d*d');
The result has the cosine similarities between all of the rows. Pick off what you need. E.g., AA(1,2) has the cosine similarity between rows 1 and 2. AA(5,8) has the cosine similarity between rows 5 and 8. Etc.
This does extra computations that you don't need, of course. But by using functions like matrix multiply that are multi-threaded I am guessing it may run faster than custom code that tries to avoid the unnecessary computations. The caveat is if the row size is too large then the memory usage may bog you down.
  9 个评论
James Tursa
James Tursa 2020-12-13
编辑:James Tursa 2020-12-13
Well, forget variable A. Simply use my code with featuresTest.
I would point out that this is the first time you have bothered to mention to me that you have extracted every 4th row into a separate variable and are trying to work with that. This would have been an important detail to mention up front.
Christian Basa
Christian Basa 2020-12-13
编辑:Christian Basa 2020-12-13
Is there a better way to store all those results into an array so I can plot the histogram for it? Or should I just do A(1,2:4), save that as a variable and then put it into an array?
Yeah, sorry. I didn't realize I forgot to mention it, so I understand why it could have been confusing. I didn't have much written up for the code yet, but what I posted is what I was working on.

请先登录,再进行评论。

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by