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 Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by