A Conversation for MATLAB - the Programming Language
matlab question
Dogster Started conversation Dec 12, 2006
I have a matlab question that nobody I've asked seems to know the answer to but ought to be obvious, perhaps the author of this entry can help?
Matlab promotes the use of vectorized code, that is if you wanted to square every element of a vector x you'd write
x = x.^2;
and not
for i=1:length(x)
x(i)=x(i)^2
end
My question is - what do you do if you have a function f whose definition you can't alter which behaves differently if passed a scalar or a vector, and you want to apply f to each element of a vector? Suppose (for the sake of argument) that abs(x) computes the absolute value of x if x is a scalar, but the length of the vector x if x is a vector. Now suppose I wanted to apply abs(x) to each scalar value in a vector x, how do I do it? At the moment, I'm stuck with doing
for i=1:length(x)
x(i) = abs(x(i));
end
but what I want is something like
x = abs(x as vector of scalars)
or something like that. Any way of doing it? In Mathematica I would write x = abs /@ x;
How about defining a function so that it can only take scalar values and not vector values?
matlab question
AlexAshman Posted Dec 12, 2006
Hmmm - I've never come across that problem before. You could try:
x = (abs(x())'
Using the colon operator to look at each scalar in the vector x should get abs to calculate a column of output values, which is then turned into the correct output using the ' operator. It works for abs, but I'm not sure if it'll work for your problem.
Alex
matlab question
AlexAshman Posted Dec 12, 2006
Ok, so it turned my reply into a smiley
Here's my post, but with the offending () replaced with {}
x = (abs(x{:}))'
Key: Complain about this post
matlab question
More Conversations for MATLAB - the Programming Language
Write an Entry
"The Hitchhiker's Guide to the Galaxy is a wholly remarkable book. It has been compiled and recompiled many times and under many different editorships. It contains contributions from countless numbers of travellers and researchers."