开发者

Storing Results of a Operation in a Matrix

开发者 https://www.devze.com 2022-12-13 03:00 出处:网络
Let\'s say I want to take the sin of 1 through 100 (in degrees). I come from a C background so my instinct is to loop 1 through 100 in a for loop (something I can do in Matlab). In a matrix/vector/ar

Let's say I want to take the sin of 1 through 100 (in degrees).

I come from a C background so my instinct is to loop 1 through 100 in a for loop (something I can do in Matlab). In a matrix/vector/array I would store sin(x) where x is the counter of the for loop.

I cannot figure out how to do this in Matlab. Do I create a array like

x = [1 .. 100];

And then do

x[offset] = numberHere;

I know the "correct" way. For operations like addition you use .+ instead of + and with a function like sin I'm pretty sure you just do

resultArray = sin(x);

I just want to know that I开发者_运维技巧 could do it the C way in case that ever came up, thus my question here on SO. :)


% vectorized
x = sin((1:100)*pi/180);

or

% nonvectorized
x=[];
for i = 1:100
   x(i) = sin(i*pi/180);
end


I beleive this can actually be done as a one liner in MatLab:

x = sind(1:100);

Note that you use sind() instead of sin(). Sin() takes radians as arguments.


As others have already pointed out there are for-loops in MATLAB as well.

help for

should give you everything you need about how it works. The difference from C is that the loop can go over objects and not only an integer:

objects = struct('Name', {'obj1', 'obj2'}, 'Field1', {'Value1','Value2'});
for x = objects
   disp(sprintf('Object %s Field1 = %d', x.Name, x.Field1))
end

That example will output:

Object obj1 Field1 = Value1
Object obj2 field1 = Value2

This could have been done as

for i=1:length(objects)
   x = objects(i);
   disp(sprintf('Object %s Field1 = %d', x.Name, x.Field1))
end

And now to what I really wanted to say: If you ever write a for loop in MATLAB, stop and think!. For most tasks you can vectorize the code so that it uses matrix operations and builtin functions instead of looping over the data. This usually gives a huge speed gain. It is not uncommon that vectorized code executes 100x faster than looping code. Recent versions of MATLAB has JIT compilation which makes it less dramatic than before, but still: Always vectorize if you can.


@Daniel Fath

I think you'll need the final line to read

resultArray(i) = sin(x(i)) (rather than x(1))

I think you can also do:

for i = x    
   ...

though that will behave differently if x is not a simple 1-100 vector


Hmm, if understand correctly you want a loop like structure

resultArray = zeros(1,length(x)) %% initialization aint necessary I just forgot how you dynamically add members :x
for i = 1:length(x) %% starts with 1 instead of zero
   resultArray(i) = sin(x(i))
end

Warning I didn't test this but it should be about right.

0

精彩评论

暂无评论...
验证码 换一张
取 消