Matlab M-File

11 visualizzazioni (ultimi 30 giorni)
Firat DAGASAN
Firat DAGASAN il 5 Ott 2016
Modificato: James Tursa il 5 Ott 2016
Consider the following vector V=[10,4,7,-8,-3,-12] Write an m file in MATLAB that doubles the elements that are negative and are divisible by 2 and/or 4, and raise to the power of 2 the elements that are positive but greater than 6.
My solution is as above, however I have not managed to run it yet...
function V(i)=[10,4,7,-8,-3,-12];
for i=1:1:6;
if [V(i)<0 | mod(V(i),2)==0 | mod(V(i),4)==0],
V(i)=V(i)*2;
end
if [V(i)>0 & V(i)>6],
V(i)=i*i;
end
V(i);
I kindly request your help. Thank you...

Risposta accettata

James Tursa
James Tursa il 5 Ott 2016
Modificato: James Tursa il 5 Ott 2016
You should review the documentation on how to write a function, since your above code is not a correctly written function. First, come up with a name for your function, e.g. myFunction. Then create a new file called myFunction.m somewhere on the MATLAB path (e.g. your working directory). Then in that file put your code. E.g.,
function result = myFunction(V)
result = V; % <-- allocate the result variable, copying all elements
%
% Insert your code here to create the result variable from the V variable
%
return
end
I will give you some hints about correcting your code:
Change this loop:
for i=1:1:6; % <-- hard coded for exactly 6 elements
to this
for i=1:numel(V) % <-- allows any size input
The following test has an error in the logic (compare this carefully with the requirement):
if [V(i)<0 | mod(V(i),2)==0 | mod(V(i),4)==0]
The following line has an error on the right hand side calculation (compare this carefully with the requirement):
V(i)=i*i;
If you don't see what the errors are, step through a small example by hand and compare that to the code result. E.g., at the command line type this:
V=[10,4,7,-8,-3,-12];
myFunction(V)

Più risposte (0)

Community Treasure Hunt

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

Start Hunting!

Translated by