Is there a better way to write this in MATLAB?

  • Context: MATLAB 
  • Thread starter Thread starter czechman45
  • Start date Start date
  • Tags Tags
    Matlab
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
3 replies · 6K views
czechman45
Messages
12
Reaction score
0
I have two matricies.
A is a 3x3x10. C is a 3x10. (A is a changing 3x3 rotation matrix and C is a changing velocity vector)
I want to multiply each 3x3 part of A with the respective 3x1 part of C.

I tried A.*C, but I get the following error: Error using ==> times Number of array dimensions must match for binary array op.
This worked:

for i=1:10
A(:,:,i)*C(:,i)
end

is there a way to not have to do it in a for loop though?

Thanks for your help.
 
Physics news on Phys.org
czechman45 said:
I have two matricies.
A is a 3x3x10. C is a 3x10. (A is a changing 3x3 rotation matrix and C is a changing velocity vector)
I want to multiply each 3x3 part of A with the respective 3x1 part of C.

I tried A.*C, but I get the following error: Error using ==> times Number of array dimensions must match for binary array op.
This worked:

for i=1:10
A(:,:,i)*C(:,i)
end

is there a way to not have to do it in a for loop though?

Thanks for your help.

I guess you must use repmat function...check on the help
 
czechman45 said:
This worked:

for i=1:10
A(:,:,i)*C(:,i)
end

is there a way to not have to do it in a for loop though?

Thanks for your help.

Short of doing it 10 times by hand. No. Why wouldn't you want to do it by a loop though. That way is most robust...

You can change
Code:
 i=1:10

to
Code:
 i=1:size(A,3)

In order to make it so no matter the amount of 3x3 matrices you have, you don't have to change the loop variable...
 
viscousflow said:
Short of doing it 10 times by hand. No. Why wouldn't you want to do it by a loop though. That way is most robust...

You can change
Code:
 i=1:10

to
Code:
 i=1:size(A,3)

In order to make it so no matter the amount of 3x3 matrices you have, you don't have to change the loop variable...

I don't know too much about MATLAB (just started this semester), but this is the best advice I could give you as a "programmer." Always and I mean ALWAYS write in your code so that things are variables. That way, if you need to re-use your code, you can just change 1 number instead of 500 numbers in every line of your code.

Besides the i =1:size thing, I can't see a faster way of doing it, but I just thought I'd add that it is almost always better to do things with variables (and long-named variables at that so you know what the variable is for).