Anybody know how to simplify this?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Israel Campiotti
am 6 Sep. 2017
Beantwortet: Walter Roberson
am 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
0 Kommentare
Akzeptierte Antwort
Walter Roberson
am 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);
0 Kommentare
Weitere Antworten (1)
Jacob Ward
am 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
0 Kommentare
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!