matlab series using for

1 view (last 30 days)
Michelle
Michelle on 20 Jun 2021
Commented: Image Analyst on 25 Jun 2021
I want to code series f = [ f(1); f(2); f(3); f(4) ] using 'for'
V = [ 1;1;1;1;1] d = [0;0;0;0;0]
Y = [ 49.86 0 0 0 49.86;
0 28.585 0 9.9597 19.919;
0 0 99.72 99.72 0;
0 0 99.72 148.44 39.839;
49.86 19.919 0 39.839 108.96]
theta = [ -85.711 0 0 0 94.289
0 -84.624 0 95.143 95.143
0 0 -85.711 94.289 0
0 0 94.289 -85.393 95.143
94.289 95.143 0 95.143 -85.217]
f(k) =
This is my code but it doesn't works as a series
f = zeros(4,1);
for k = 1:4
sum = 0;
for n = 1:5
sum = sum + V(k)*Y(k,n)*V(n)*cos(deg2rad(d(k)-d(n)-theta(k,n)))
end
f(k) = sum
end

Answers (1)

Image Analyst
Image Analyst on 20 Jun 2021
Edited: Image Analyst on 20 Jun 2021
You did not ask any questions. You just made an announcement. I assume you'd like to ask for advice.
Tips:
  1. Don't use sum as the name of your variable since it's a built-in function.
  2. Instead of cos(deg2rad(angleInDegrees)), use cosd(angleInDegrees). cosd() is a special function where you can input degrees directly so you don't need to convert the variable to radians explicitly.
  3. What's the point of your d being all zeros?
  3 Comments
Mathieu NOE
Mathieu NOE on 25 Jun 2021
hello
on my side I didn't find an obvious bug in your code
why do you say the summation does not work ?
Image Analyst
Image Analyst on 25 Jun 2021
This works fine:
clc; % Clear the command window.
fprintf('Beginning to run %s.m ...\n', mfilename);
close all; % Close all figures (except those of imtool.)
clearvars;
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 13;
V = [1;1;1;1;1]
d = [0;0;0;0;0]
Y = [49.86 0 0 0 49.86;
0 28.585 0 9.9597 19.919;
0 0 99.72 99.72 0;
0 0 99.72 148.44 39.839;
49.86 19.919 0 39.839 108.96]
% Declare theta in degrees.
theta = [-85.711 0 0 0 94.289
0 -84.624 0 95.143 95.143
0 0 -85.711 94.289 0
0 0 94.289 -85.393 95.143
94.289 95.143 0 95.143 -85.217]
f = zeros(4,1);
for k = 1:4
theSum = 0;
for n = 1:5
angle = d(k) - d(n) - theta(k, n); % In degrees, so we can use cosd()
theSum = theSum + Y(k,n) * V(n) * cosd(angle);
end
f(k) = V(k) * theSum;
end
f
fprintf('Done running %s.m\n', mfilename);
Do you have any problem with it?

Sign in to comment.

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!