Problem storing array value in MATLAB

  • Context: MATLAB 
  • Thread starter Thread starter geft
  • Start date Start date
  • Tags Tags
    Array Matlab Value
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
4 replies · 4K views
geft
Messages
144
Reaction score
0
I have the following function

Code:
function [W] = calcw(k1,k2,d,x)

if x<d
    W = k1*x;
elseif x>=d
    W = k1*x+2*k2*(x-d);
end;

save('varw.mat');

with the following script
Code:
k1 = 10e4;
k2 = 1.5e4;
d = 0.1;
x = 0:0.01:0.3;
    
weight = calcw(k1,k2,d,x);

plot(weight,x);

but the problem is that the W values refuse to be stored in the weight variable in the form of an array. The code works if x is a single value, but it doesn't since x is an array. Any help please?
 
Physics news on Phys.org
When you use a comparison on an array the way you currently have it, MATLAB will only evaluate the code under the condition if it is true for every element in the array.

Code:
if x<d
    W = k1*x; % This will only happen if *all* elements of x < d
elseif x>=d
    W = k1*x+2*k2*(x-d); % This will only happen if all elements of x >= d
end
I suspect you want to create a vector W that weights the individual elements of the input x vector. You'll need a for loop and to access the individual members of the x vector then.
 
Do you mean using something like this?

Code:
for i = 1:length(x)
weight[i] = calcw(k1,k2,d,x[i]);
end;

I keep getting parse errors for the '=' and ')'.
 
Your syntax is incorrect. In MATLAB, to call an element of a matrix/vector, use
Code:
% Vector (i.e. a 1 x n or n x 1 matrix)
someElement = vector(i); % i is some integer 1< i < length(matrix)
% Matrix
someElement = matrix(i,j); % i,j are ints such that 1<i<number of rows and 1<j<number of columns

I would vectorize the function instead, like this:
Code:
function [W] = calcw(k1,k2,d,x)
    W = zeros(1,length(x)); % initialize W
    for i=1:length(x);
        if x(i)<d
            W(i) = k1*x(i);
        elseif x(i)>=d
            W(i) = k1*x(i)+2*k2*(x(i)-d);
        end % end if
    end % end for
end % end function
Then you can just call:
Code:
weight = calcw(k1,k2,d,x);
 
Last edited:
It works! Many thanks :)