Mo Samani
Mo Samani

Reputation: 53

How to repeat calculations but with different value

I'm a beginner working on a matlab project recently, in a part of my work,I have to do the calcultions for different values of k(as described in the code summary), the question is how can I do the calculations again with different k , without copy/pasting the code again ?

clc
clear
Tinf = 15;
h = 100;
Tb = 200;
k = 204;
L = 9e-2;
DL = L / 9;
D = 3e-2;
A = zeros(170,170);
C1 = -k * pi * (D/8) ^ 2 / DL;
C2 = -k * DL * pi / 4 * D / 8 / (D/4);
Cntr = 1 : 17 : 170;
Con = zeros(170,1);
%rest of the code which has variables of K

Upvotes: 0

Views: 250

Answers (2)

EBH
EBH

Reputation: 10450

Here's a short code for that, using anonymous functions:

% Parameters:
L = 9e-2;
DL = L / 9;
D = 3e-2;

% Functions:
C1 = @(k) -k * pi * (D/8) ^ 2 / DL;
C2 = @(k) -k * DL * pi / 4 * D / 8 / (D/4);

% Variable (assuming the calculation is on int from 1 to 100):
k = 1:100;

% Result:
y1 = C1(k)
y2 = C2(k)

y1 is simply the result of function C1(k), and the same for y2. Hope that's clear enough ;)

Upvotes: 2

jarmond
jarmond

Reputation: 1382

Drop the lines

clc
clear

and the line assigning to k. Then turn it into a function (called, e.g., calculation) file instead of a script file by adding the line

function result=calculation(k)

at the top. In your calculation leave the answer in the result variable and it will be returned from your function.

Upvotes: 2

Related Questions