Prev: Reading from Csv File
Next: show to save a matlab generated image to specific location in GIF format
From: radar on 22 May 2010 15:45 I'm sure there's a better way to do this. I have a row vector of outcomes. From it, I want to create a matrix and a row vector. The matrix called samples is built by taking 3 contiguous outcomes and putting them into a column, increment by 1, take the next three, and so on. The row vector called targets is built by taking the outcome adjacent to the last outcome in the groups of 3. This code works, but I'm sure it can be done better, can't it? samples = []; targets = []; for k = 1:length(outcomes)-3 s3 = outcomes(k:k+2); samples = [samples; s3]; t4 = outcomes(k+3); targets = [targets; t4]; end; smp = smp'; tg = tg';
From: radar on 22 May 2010 15:47 please ignore last two lines. I guess there is no way to edit your posts on this forum
From: Ashish Uthama on 24 May 2010 14:08 On Sat, 22 May 2010 19:45:59 -0400, radar <able(a)tds.net> wrote: for one, you can remove targets out from the loop: tagets = outcomes(4:end)
From: Matt Fig on 24 May 2010 15:54 There are better ways to do what you want. Even with a FOR loop there are more efficient ways. It is always a good idea to avoid growing an array in a loop where avoidable. Here is a FOR loop which avoids this problem: samples = zeros(length(outcomes)-3,3); % This is pre-allocation. targets = zeros(length(outcomes)-3,1); for k = 1:length(outcomes)-3 samples(k,:) = outcomes(k:k+2); targets(k) = outcomes(k+3); % There is really no reason for this! end Now the next step is to try and vectorize the problem using built-in MATLAB functions. This will usually involve indexing and/or temporary array creation. Here is one way to do it: samples2 = ones(length(outcomes)-3,3); samples2(:,1) = 1:length(outcomes)-3; samples2 = outcomes(cumsum(samples2,2)); targets2 = outcomes(4:end).'; % This one is trivial. For a large outcomes array (1,9000), the vectorized version is 23 times faster than the above FOR loop, which is 25 times faster than your FOR loop.
From: radar on 26 May 2010 17:49 I apologize for the delay in responding. Thank you very much for your exposition. This is exactly what I was looking for to help get better at programming in matlab.
|
Next
|
Last
Pages: 1 2 Prev: Reading from Csv File Next: show to save a matlab generated image to specific location in GIF format |