How can I implement multi element arrays/vectors into my program?

function [val] = jaa369_ClipData(data,max_val,min_val)
%jaa369_ClipData - function to ensure data does not exceed max_val and min_val
if (data >= max_val)
val=max_val
elseif (data<=min_val)
val=min_val
else
val=data
end
The goal of this function is to accept a variable called data and check if it is greater than or equal to max val. If it is then the results returned (val) is to be set equal to max val, otherwise (else) the result is to be set to equal data. However I wanna set it up so that the value input for data can be a vector of many values. The function should go through each of these values and test whether or not each input value value is greater than the max val or less than the min value supplied to the function. If the the current input value of data is greater than or equal to max val then the result of the function should be set to max val. If the the current input value of data is less than or equal to min val then the result of the function should be set to min val.

 Réponse acceptée

Ameer Hamza
Ameer Hamza le 11 Sep 2020
Modifié(e) : Ameer Hamza le 11 Sep 2020
Try this
max(min(x, max_val), min_val)
To write it in the function
function [val] = jaa369_ClipData(data,max_val,min_val)
val = max(min(x, max_val), min_val);
end

4 commentaires

Will this let me type in a list of numbers such as [5,-2,9,-7] for example? and if so how would I be able to run it? I am new to MATLAB so I am a bit unsure.
First, create a file named jaa369_ClipData.m and save the following code in it.
function [val] = jaa369_ClipData(data,max_val,min_val)
val = max(min(data, max_val), min_val);
end
and then in the command window, you can call this function and pass input values. For example
jaa369_ClipData([-3 4 -2 11 3 -2 -9], -2, 2)
I tried this but it's giving me the following error:
Unrecognized function or variable 'x'.
Should I rename 'x' to 'data'?
There was a mistake; see the updated code in my last comment.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by