is it possible to use a function in a vectorization
조회 수: 6 (최근 30일)
이전 댓글 표시
is it at all possible to use function like sum, mean, or sqrt within a vectorization? for example
output(:,3) = sum([ output(:,1) output(:,2) ])
I know that in this case it is simple to just add the two columns without using sum, but I want to use several functions in a more complicated computation, however I can't even get this to work.
채택된 답변
Jan
2011년 10월 31일
The colon operator is not defined for vectors. Therefore constantError(:,1)*16-15:constantError(:,1)*16 does not create the expected results. But I'm surprised, that it does not create an error.
a = constantError(:,1)*16-15; % [1; 17; 33; 49; 65]
b = constantError(:,1)*16; % [16; 32; 48; 64; 80]
a:b % 1:16
This is the same as a(1):b(1).
But the problem can be solved easier and faster:
sum(reshape(output(:, 1), 16, []), 1) / 16
In addition I'm using sum()/n directly, which is faster than mean.
댓글 수: 1
Andrei Bobrov
2011년 10월 31일
n= 5
constantError = [(1:n)', mean(reshape(output,[],numel(output)/n),2)];
추가 답변 (5개)
Jan
2011년 10월 31일
As you can see by running your example, it is possible. Even more, it is the idea behind vectorization to use function inside the vectorization.
If you fail with a complicated computation, post it here together with the occurring error messages.
Note: Your example looks strange. If output is a nx3 matrix, the sum will reply a 1x2 vector, But this is unlikely to match into output(:, 3). Posting real examples is usually better.
댓글 수: 2
Jan
2011년 10월 31일
Is constantVector a [1 x N] row vector?
It is hard to guess such details, and if my guessing is wrong, I'm not helping but confusing you. Please post an example of the code, which inlcude all relevant parts (but not more) and which runs except for the line causing troubles.
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!