How do i need to change the code to get the y returned as a vector?
% global x y
for x=0:0.1:(2*pi)
if x<1
funkcija1();
end
if x>1
funkcija2();
end
end
plot(y,'r:s')
of course i have created my functions in separate files:
%function funkcija1
global x y
y=sin(x)+cos(x);
end
%function funkcija2
global x y
y=sin(x)-cos(x);
end
so when i plot everything i just get a dot and i need a full graph. What could be wrong with the code?

2 Comments

Stephen23
Stephen23 on 28 Oct 2018
Edited: Stephen23 on 28 Oct 2018
"What could be wrong with the code?"
Using global variables, instead of passing the data simply and efficiently as input/output arguments.
But my task is to use global variables. The code works, but using plot function i must make a graph which would draw some kind of a line, but it just draws one dot

Sign in to comment.

 Accepted Answer

Yes.
I have no idea what you intend. Also, global variables cause more problems than they solve. Do not use them.
Calling routine:
x=0:0.1:(2*pi);
for k = 1:numel(x)
if x(k)<1
y(k) = funkcija1(x(k));
xp(k) = x(k);
end
if x>1
y(k) = funkcija2(x(k));
xp(k) = x(k);
end
end
plot(xp, y)
Functions:
function y = funkcija1(x)
y=sin(x)+cos(x);
end
function y = funkcija2(x)
y=sin(x)-cos(x);
end
Experiment to get the result you want.

4 Comments

In my task i must use global variables and functions cant be the way you wrote them. I just need that the plot function would draw a line and not a single dot, but have no clue what to do
@Dominykas Repecka: please show us the task you have been given.
My task is not in english, so i'll try to translate:
Create scripts and functions that would swap tha data only using global variables. Create a script, where the vector x is generated from 0 to 2*pi with a step 0,1. Vector should be trasnferred to a function that would calculate either sin(x)+cos(x) when x<1 or to a function that calculates sin(x)-cos(x) when x>1 and then returns the result back to the script. The script then must draw a graph with a dotted red line, with square markers.
Then it says: Create 3 files - 2 functions and 1 script. Functions should not have input/output and the wanted data should only be transferred only using global variables. When the input/output is not used, declaring and calling should be used only it's name and there shouldnt be anything else next to the name from the left nor right.
@Dominykas Repecka: hopefully this assignment is intended as a demonstration of how not to write code.
You will have to initialize the output variable to an empty array and concatenate into it with each function call. Or do something similar with indexing.

Sign in to comment.

More Answers (0)

Categories

Find more on Mathematics 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!