Anybody know how to simplify this?

4 vues (au cours des 30 derniers jours)
Israel Campiotti
Israel Campiotti le 6 Sep 2017
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

Réponse acceptée

Walter Roberson
Walter Roberson le 6 Sep 2017
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);

Plus de réponses (1)

Jacob Ward
Jacob Ward le 6 Sep 2017
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

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by