Anybody know how to simplify this?
2 次查看(过去 30 天)
显示 更早的评论
I have two pieces of code that I would like to know if there is another way to write them
for i = 1:m
for j = 1:n
H(j,i) = some_function(W(i,:),X(j,:));
end
end
and
for i = 1:n
Y(i,:) = other_function(Y(i,:));
end
0 个评论
采纳的回答
Walter Roberson
2017-9-6
If you have the stats toolbox, then
H = pdist2(W, X, @somefunction)
For the other one, I cannot think of any way to simplify the code. There are other ways of writing it, such as
Y = cell2mat( arrayfun(@(i) other_function(Y(i,:)), (1:size(Y,1)).', 'uniform', 0) );
but I would by no means say that is simpler or more efficient.
There is a special case that can be written more simply: if Y is a table or timetable, then https://www.mathworks.com/help/matlab/ref/rowfun.html
Y = rowfun(@otherfunction, Y);
0 个评论
更多回答(1 个)
Jacob Ward
2017-9-6
Not sure about the first one, but for the second one, the for loop and indexing is unnecessary. See this example:
This...
>> M = [0 1 2; 3 4 5; 6 7 8];
>> for i = 1:3
>> M(i,:) = sin(M(i,:));
>> end
M =
0 0.8415 0.9093
0.1411 -0.7568 -0.9589
-0.2794 0.6570 0.9894
Yields the same results as...
>> M2 = [0 1 2; 3 4 5; 6 7 8];
>> M2 = sin(M2);
M2 =
0 0.8415 0.9093
0.1411 -0.7568 -0.9589
-0.2794 0.6570 0.9894
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!