Anybody know how to simplify this?

조회 수: 2 (최근 30일)
Israel Campiotti
Israel Campiotti 2017년 9월 6일
답변: Walter Roberson 2017년 9월 6일
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

채택된 답변

Walter Roberson
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);

추가 답변 (1개)

Jacob Ward
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

카테고리

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