# I am trying to create a function form a vector from my matrix and I do not understand where my mistake is?

1 Ansicht (letzte 30 Tage)
Laurence Guevremont am 27 Sep. 2016
Kommentiert: dpb am 29 Sep. 2016
function A=combined (V)
for V(k)= A(i,j)
k=1;
for
i=1;
j=1;
k=k+1;
end
end
##### 3 Kommentare1 älteren Kommentar anzeigen1 älteren Kommentar ausblenden
Laurence Guevremont am 27 Sep. 2016
Bearbeitet: Laurence Guevremont am 27 Sep. 2016
Ok so I need transform my matrix into a vector so example: A= [1 2 3; 4 5 6; 7 8 9] And then form a vector A A=[1 2 3 4 5 6 7 8 9]
My function right now does not work, there is a mistake on line 2
dpb am 27 Sep. 2016
Indeed, there are several issues but the one of defining the for...end loop indices and range is key. To do the requested function, using "linear addressing" would be a good way to proceed. Look those up in the documentation and study for loops...

Melden Sie sich an, um zu kommentieren.

### Antworten (3)

Moe_2015 am 27 Sep. 2016
Bearbeitet: Moe_2015 am 27 Sep. 2016
You should avoid using a for loop here. You can do something like this:
function myVector=combined(myMatrix)
myVector = reshape(myMatrix,1,numel(myMatrix));
end
##### 1 Kommentar-1 ältere Kommentare anzeigen-1 ältere Kommentare ausblenden
Laurence Guevremont am 27 Sep. 2016
But I need to create a function I cannot use one already made by matlab

Melden Sie sich an, um zu kommentieren.

dpb am 27 Sep. 2016
"...transform my matrix into a vector"
Really don't need a function for this; Matlab has syntax to do it already. A previous answer shows reshape, except I'd suggest to simply use it ( reshape, that is) inline as shown there in the function instead.
There's another Matlab idiom that's even more compact--
A=A(:).'; % convert A of unspecified dimensions to row vector
NB: the .' transpose operator to return the requested row vector instead of the column vector colon returns.
##### 2 KommentareKeine anzeigenKeine ausblenden
Laurence Guevremont am 27 Sep. 2016
But I need to create a function I cannot use one already made by matlab
dpb am 27 Sep. 2016
Then wrap the above inside the function wrapper. Unless the assignment also requires a loop be used???

Melden Sie sich an, um zu kommentieren.

James Tursa am 28 Sep. 2016
Here is an outline of what you need to be using for the for loops (seems to be a requirement for this assignment).
% Insert any initialization code here
for i = 1:size(V,1)
for j = 1:size(V,2)
% Insert your assignment etc code here
end
end
##### 1 Kommentar-1 ältere Kommentare anzeigen-1 ältere Kommentare ausblenden
dpb am 29 Sep. 2016
If OP is clever, this can be done with one loop... :)

Melden Sie sich an, um zu kommentieren.

### Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by