How to generate a matrix through a loop? - matlab

I´m wondering how to get these in Matlab:
a =
1 3
2 4
3 5
4 6
5 7
6 8
7 9
8 10
9 11
10 12
Really the structure I want to do has 2 thousand files. but I will start with something easier.
So I was thinking about to do it throught a loop:
for i=1:1:10
a(i) = [i i+2]
end
but this give an error:
??? In an assignment A(I) = B, the number of elements in B and
I must be the same.
The idea is to generate a entire matrix (or structure, I suppose both are the same...) using a for loop (or may be there is a way to do it without any case of loop...).
Does anyone could tell me how to do it?
Thank you so much!

In your for loop, you are assigning two numbers to one element of your array a. Try
for i=1:1:10
a(i,:) = [i i+2];
end
instead. Or, just use
a=[(1:10)' (3:12)'];
which replaces your loop...

The specific matrix, w/o loops, where n is no. of rows:
n=10;
a=(1:n)';
m=[a a+2];

Related

How do I populate dynamic arrays in Julia similar to Matlab

My understanding of programming languages is limited, I have started 'coding' with matlab and wanted to transfer a simulation of mine from matlab to julia because there is no licensing fee. What I would like to know is in MATLAB I can auto populate array without ever initializing an array, while I know it is an inefficient way to it, I would like to know if there is similar way to do it on Julia.
Ex in MATLAB
for a in 1:10
x(a)=a;
end
will give me an array x = [ 1 2 3 4 5 6 7 8 9 10], is there a similar way to do that in julia? The way I have been doing it is declaring an empty array using Float64[] and append to it but it doesn't work the same way if the array is multidimensional.
my implementation in Julia for a 1D array
x = Float64[]
for a in 1:10
append!(x,a)
end
Any help regarding this will be greatly appreciated. Thank you!!!
MATLAB explicitly warns against the way you write this code and advises to preallocate for speed.
Julia, OTOH, cares more about performance and prohibits such pattern from the beginning. At the same time, it allows for more convenient and fast alternatives to do the same task.
julia> x = [a for a = 1:10] # OR x = [1:10;]
10-element Vector{Int64}:
1
2
3
4
5
6
7
8
9
10
and for 2D arrays,
julia> x = [i+j-1 for i = 1:5, j = 1:5] # OR x = (1:5) .+ (1:5)' .- 1
5×5 Matrix{Int64}:
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9
And you have other convenience functions, like zeros(m,n), fill(val, dims), rand(Type, dims), etc., that you can use to initialize the arrays however you want.
Although #AboAmmar is correct that this generally isn't a good pattern, your code works if you use push! instead of append!. push! adds an element to a vector. append appends 2 vectors.

How to add a matrix and a vector in MATLAB considering positions

I have this little problem and I hope that you can help me.
My question is about if there is someway to make this operation in MATLAB:
Suppose this matrix called A(4x3):
A=[1 2 3;4 5 6;7 8 9;8 9 1];
and this vector array called B (4x1):
B=[1;3;5;0];
Now the operation that I want to make is kinda simple: A+B=C, where C is:
A + B = C
C=[2 3 4;7 8 9;12 13 14;8 9 1];
As you can see, the first row of the matrix C is the sum between the first row of matrix A with the first value of the vector B, and it continues.
I know how to make it easily using a "for" but I want to know if there's a way to make it faster.
bsxfun [Apply element-by-element binary operation to two arrays with singleton expansion enabled] with a function handle #plus might just work for you. It lets B expand onto the second dimension as needed for operating with A which is already a 2D matrix and thus giving you the desired "summation" output -
bsxfun(#plus,A,B)

Accumarray how to set "fun" to use only last obs of each bin

Is there a way to let accumarray drop every observation but the last of each group?
What I had in mind was something similar:
lastobs=accumarray(bin,x,[],#(x){pick the observation with the max index in each group};
To give you an example, suppose I have the following:
bin=[1 2 3 3 3 4 4]; %#The bin where the observations should be put
x= [21 3 12 5 6 8 31]; %#The vector of observations
%#The output I would like is as follow
lastobs=[21 3 6 31];
I am actually thinking of accumarray only because I just used it to compute the mean of the observations for each bin. So every function that could make the trick would be fine for me.
Of course you can do this with accumarray. x(end) is the last observation in an array. Note that bin needs to be sorted for this to work, so if it isn't, run
[bin,sortIdx]=sort(bin);x = x(sortIdx); first.
lastobs = accumarray(bin(:),x(:),[],#(x)x(end)); %# bin, x, should be n-by-1
You already got your accumarray answer, but since you are looking for any solution that will do the job, consider the following application of unique.
Using unique with the 'legacy' option gives the index of the last occurrence of each value, as you need:
>> [~,ia] = unique(bin,'legacy')
ia =
1 2 5 7
>> lastobs = x(ia)
lastobs =
21 3 6 31
Now, I love accumarray, as many here are aware, but I actually prefer this solution.

MATLAB: copy a specific portion of an array

I am trying to copy a few elements from a matrix, but not a whole row, and not a single element.
For example, in the following matrix:
a = 1 2
3 4
5 6
7 8
9 0
How would I copy out just the following data?
b = 1
3
5
i.e. rows 1:3 in column 1 only... I know that you can remove an entire column like this:
b = a(:,1)
... and I appreciate that could just do this and then dump the last two rows, but I'd like to use more streamlined code as I am running a very resource-intensive solution.
Elements in a matrix in MATLAB are stored in column-major order. Which means, you could even use a single index and say:
b = a(1:3);
Since the first 3 elements ARE 1,3,5. Similarly, a(6) is 2, a(7) is 4 etc. Look at the sub2ind method to understand more:
http://www.mathworks.com/help/techdoc/ref/sub2ind.html
You are not "removing" the second column, you are referencing the other column.
You should read some of the Matlab docs, they provide some help about the syntax for accessing portions of matrices:
http://www.mathworks.com/help/techdoc/learn_matlab/f2-12841.html#f2-428

Compare two vectors in Matlab

I think, the question might have already been asked before. But I could not find proper answer in this forum.
Acutally, I have 2 vectors( of unequal length). I need to compare the 2 vectors. I can do it using a for loop. But it is taking a very long time.
Any obvious method which I may be missising ?
here is a small code snippet:
a=[ 1 2 3 4 5 6 7 8 1 2 3 4];
b=[ 2 3 4];
How can we compare a and b. Basically I need the index in vector a when comparison returns true.
Thanks
You can use strfind() for this (it works with doubles):
idx = strfind(a, b);
idx will contain the indices of all matches.