write two matlab vectors in a file and insert backslash between the vectors - matlab

Given
a=[1 2 3];
b=[4 5 6];
Output in file should look like:
1 2 3 / 4 5 6
Is there a way to achieve this in one single fprintf() call?
I have a solution where there is no backslash between a and b
fprintf(fileID, '%d %d ', a, b);
output:
1 2 3 4 5 6 (no backslash in between)

You can get a single call to fprintf if you’re willing to construct your format string dynamically.
fileID=1;
a=[1,2,3];
b=[4,5,6,7];
c=[8,9];
fprintf(fileID,strjoin(cellfun(#(c)sprintf('%d ',c),{a,b,c},'UniformOutput',false),'/ '));
It’s not pretty, and it’s probably only worth the trouble if you’ve got a lot of calls to fprintf in a loop and need to avoid overhead, but technically it achieves what you asked for.

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.

Average on contiguos segments of a vector

I'm sure this is a trivial question for a signals person. I need to find the function in Matlab that outputs averaging of contiguous segments of windowsize= l of a vector, e.g.
origSignal: [1 2 3 4 5 6 7 8 9];
windowSize = 3;
output = [2 5 8]; % i.e. [(1+2+3)/3 (4+5+6)/3 (7+8+9)/3]
EDIT: Neither one of the options presented in How can I (efficiently) compute a moving average of a vector? seems to work because I need that the window of size 3 slides, and doesnt include any of the previous elements... Maybe I'm missing it. Take a look at my example...
Thanks!
If the size of the original data is always a multiple of widowsize:
mean(reshape(origSignal,windowSize,[]));
Else, in one line:
mean(reshape(origSignal(1:end-mod(length(origSignal),windowSize)),windowSize,[]))
This is the same as before, but the signal is only taken to the end minus the extra values less than windowsize.

alternative to reshape or colon in matlab

I want to reduce a two dimensional matrix to row vector.
But using reshape with large matrices is really slow. The other alternative is to use colon, but i want matrix's transpose to be colon and not the matrix itself.
e.g.
A=magic(3)
A =
8 1 6
3 5 7
4 9 2
A(:) will stack up all the columns one by one. but i am looking for something like this:
AA=A(2:3,:)';
and then reshape or colon AA instead of A.
The issue is i dont want to define additional variable like AA.
Is there anyway to reduce dimension of two dimensional matrix without reshape?
You can avoid the additional variable by linear indexing. For your example:
A([2 5 8 3 6 9])
which gives
3 5 7 4 9 2
What's happening here is that you treat A as if it was already transformed into a vector, and the elements of this one-dimensional array are accessed through indices 1 through 9. Using the colon is a special case of linear indexing, A(:) is the same as A(1 : end).
Figuring out the right linear indices can be tricky, but sub2ind can help with that.
It is possible that this slightly speeds up the code, mainly because (as #Shai wrote) you avoid writing data to an intermediate variable. I wouldn't expect too much, though.
Try looking at subsref. For your example, you could use it as follows:
subsref(A',struct('type','()','subs',{{2:3,':'}}))
Update: I misunderstood the original question; I thought the OP wanted to select rows from 2:3 from the transposed A matrix keeping the columns as is. I will keep the previous answer in case it could be useful to others.
I think he/she could use the following to slice and flatten a matrix:
subsref(A(2:3,:)', struct('type','()','subs',{{':'}}))
This would give as output:
[3 5 7 4 9 2]'

How to generate a matrix through a loop?

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];

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.