Pages

Showing posts with label Function. Show all posts
Showing posts with label Function. Show all posts

18.7.12

Concatenate arrays with different sizes in Matlab

Sometimes you want to concatenate arrays with different sizes, and Matlab doesn't allow you to. This makes sense, of course, but still you just want to put all that stuff together for some reason. Then this function may help you. As any other functions I've wrote, I'm sure it an be optimized, so I'll be happy to hear suggestions.
You can also download it from my matlab file exchange and rate it :-)



function [catmat]=padconcatenation(a,b,c)
%[catmat]=padconcatenation(a,b,c)
%concatenates arrays with different sizes and pads with NaN.
%a and b are two arrays (one or two-dimensional) to be concatenated, c must be 1 for
%vertical concatenation ([a;b]) and 2 for horizontal concatenation ([a b])
%
% a=rand(3,4)
% b=rand(5,2)
% a =
%
%     0.8423    0.8809    0.7773    0.3531
%     0.2230    0.9365    0.1575    0.3072
%     0.4320    0.4889    0.1650    0.9846
% b =
%
%     0.6506    0.8854
%     0.8269    0.0527
%     0.4742    0.3516
%     0.4826    0.2625
%     0.6184    0.5161
%
% PADab=padconcatenation(a,b,1)
% PADab =
%
%     0.8423    0.8809    0.7773    0.3531
%     0.2230    0.9365    0.1575    0.3072
%     0.4320    0.4889    0.1650    0.9846
%     0.6506    0.8854       NaN       NaN
%     0.8269    0.0527       NaN       NaN
%     0.4742    0.3516       NaN       NaN
%     0.4826    0.2625       NaN       NaN
%     0.6184    0.5161       NaN       NaN
%
% PADab=padconcatenation(a,b,2)
%
% PADab =
%
%     0.8423    0.8809    0.7773    0.3531    0.6506    0.8854
%     0.2230    0.9365    0.1575    0.3072    0.8269    0.0527
%     0.4320    0.4889    0.1650    0.9846    0.4742    0.3516
%        NaN       NaN       NaN       NaN    0.4826    0.2625
%        NaN       NaN       NaN       NaN    0.6184    0.5161

sa=size(a);
sb=size(b);

switch c
    case 1
        tempmat=NaN(sa(1)+sb(1),max([sa(2) sb(2)]));
        tempmat(1:sa(1),1:sa(2))=a;
        tempmat(sa(1)+1:end,1:sb(2))=b;
       
    case 2
        tempmat=NaN(max([sa(1) sb(1)]),sa(2)+sb(2));
        tempmat(1:sa(1),1:sa(2))=a;
        tempmat(1:sb(1),sa(2)+1:end)=b;
end

catmat=tempmat;
end

3.5.12

Custom Colors for Matlab Plots


This is a(nother) simple function I wrote for matlab, it can also be downloaded from my file exchange at mathworks:
http://www.mathworks.com/matlabcentral/fileexchange/36514-custom-colors-for-plots

In plot graphs, often it's needed to use a several colors that can be easily differentiated on a first look on the graphic. With this function you can call easily (by name or by code) a selection of 15 colors.
It's very simple and there are more elegant ways to do it, but I think it's a very functional solution.


function ccol=CustomColors(ct1)
%This is a function to create some easy to differentiate colors, very
%useful when plotting many things in the same graphic
%The RGB coordinates and names where taken from the following page:
%http://web.njit.edu/~kevin/rgb.txt.html
%
%Examples:
%for ccc=1:15
%plot(ccc*ones(1,10),'Linewidth',4,'Color', CustomColors(ccc))
%end
%
%plot(ones(1,10),'Linewidth',4,'Color', CustomColors('Coral'))
%plot(ones(1,10),'Linewidth',4,'Color', CustomColors('DeepSkyBlue4'))
%
%Copyright: Andres Gonzalez. 2012.

CColors={
    [   [0,0.407843137254902,0.545098039215686] ];% DeepSkyBlue4
    [   [0.545098039215686,0.270588235294118,0.0745098039215686]    ];% SaddleBrown
    [   [0,0.803921568627451,0] ];% green3
    [   [0,0.498039215686275,1] ];% SlateBlue
    [   [0.956862745098039,0.643137254901961,0.376470588235294] ];% SandyBrown
    [   [0.419607843137255,0.556862745098039,0.137254901960784] ];% OliveDrab
    [   [0.800000000000000,0.196078431372549,0.600000000000000] ];% Violet,Red
    [   [0.556862745098039,0.419607843137255,0.137254901960784] ];% Sienna
    [   [0.803921568627451,0.678431372549020,0] ];% gold3
    [   [0.545098039215686,0,0.545098039215686] ];% magenta4
    [   [1,0.498039215686275,0] ];% coral
    [   [1,0.843137254901961,0] ];% gold1
    [   [0.600000000000000,0.196078431372549,0.800000000000000] ];% DarkOrchid
    [   [0.941176470588235,0.501960784313726,0.501960784313726] ];% LightCoral
    [   [0.635294117647059,0.803921568627451,0.352941176470588] ];% DarkOliveGreen3
   
    };
NColors={
    'DeepSkyBlue4';
    'SaddleBrown';
    'Green3';
    'SlateBlue';
    'SandyBrown';
    'OliveDrab';
    'VioletRed';
    'Sienna';
    'Gold3';
    'Magenta';
    'Coral';
    'Gold1';
    'DarkOrchid';
    'LightCoral';
    'DarkOliveGreen3';
    };

switch class(ct1)
    case 'double'
        if ct1<1
            ct1=1
            disp(sprintf('Color index must be between 1 and %d, taking closest value [%d]',length(CColors),ct1))
        elseif ct1>length(CColors)
            ct1=length(CColors)
            disp(sprintf('Color index must be between 1 and %d, taking closest value [%d]',length(CColors),ct1))
        end
       
       
       
    case 'char'
        ctfound=0
        for ct2=1:length(NColors)
            if (strcmp(NColors{ct2},ct1))
                ctfound=ct2
            end
        end
        if ctfound==0
            disp(sprintf('Color not found taking default value [%d]',1))
        else
            ct1=ctfound
        end
       
    otherwise
        disp(sprintf('Color not valid taking default value [%d]',1))
       
       
end





ccol=CColors{ct1}
end






17.4.12

Save Workspace to Struct

This was a nice function that I created today, and it allows to save all the variables from the "base" workspace to a single struct, in order to have them all nicely packed in case you want to create mat file with them and later reload it without having so much worry of overwriting the variables in the other workspace. I gratefully accept suggestions for better options.
And now it's also available at the Matlab Central (if you want to rate it, which is always welcome):  http://www.mathworks.com/matlabcentral/fileexchange/36257-save-workspace-to-struct

%This Script saves all the variables from the current workspace into a
%single structure array.
%Created by Andres Gonzalez. 2012

function WStruct=ws2struct()

WSVARS = evalin('base', 'who');
for wscon=1:size(WSVARS,1)
    thisvar=evalin('base', WSVARS{wscon});
    eval(strcat('THEWORKSPACE.(WSVARS{wscon})=thisvar;'))
end

WStruct=THEWORKSPACE;

27.12.11

Merging Multiple Cells into Single One in Excel

These are very simple and useful macros to concatenate the content of multiple cells, merging it into one cell.

'Macros for Horizontal and Vertical concatenation

'Copyright, Andrés Gonzalez, 2008

Sub mezclar() 'horizontal concatenation

For Each fila In Selection.Rows

mensaje = ""

For Each celda In fila.Cells

mensaje = mensaje & celda.Value & " "

Next

fila.Clear

fila.Cells(1, 1).Value = mensaje

Next

End Sub

Sub mezclarV() 'vertical concatenation

For Each columna In Selection.Columns

mensaje = ""

For Each celda In columna.Cells

mensaje = mensaje & "- " & celda.Value & Chr(10)

Next

columna.Clear

columna.Cells(1, 1).Value = mensaje

Next

End Sub


Let's say you have the following table:

Albert

Einstein

Nikola

Tesla


With the first macro the result will be:

albert einstein

nikola tesla


And with the second, it will be:

- albert
- nikola

- einstein
- tesla


I think this one is cool, isn't it?

20.12.11

Replace Error Message with Custom Message in Excel

Another simple function... there are other ways to do it, but this one seems faster to me

'This function takes away errors in formulas and replace them for something

'more meaningful (a string defined by the user)

'example: quitarerror(1/0;"you can't divide by zero")

' result:"you can't divide by zero"

'Copyright, Andrés González, 2008

Function quitarerror(dato As Variant, reemplazo As Variant) As Variant

If IsError(dato) = True Then

quitarerror = reemplazo

Else

quitarerror = dato

End If

End Function

21.6.11

Resample a Matrix in Matlab

This function does the same as the previous one (resample) but for a matrix. Again, maybe not the most elegant, but works


function newmatrix=resampmatrix(matrix,newlen)

%----------------

%this function uses linear interpolation to change the number of rows in a

%matrix.

%Copyright, 2011, Andrés González


%----------------

[rows cols]=size(matrix);

newmatrix=[];

for i=1:cols

len=rows;

x=1:len;x=x';y=matrix(:,i);

xx=1:(len-1)/(newlen-1):len;

xx=xx';

yy=interp1(x,y,xx,'linear');

newmatrix=[newmatrix yy];

end

Resample in Matlab

This is a simple function to resample a vector in matlab. I now there might be more elegant ways to do it, but this one works and it's simple

function newvector=resample(vector,newlen)

%%%%%%%%%%%%%%%%%%%%

%This function uses linear interpolation to change the number of samples

% Copyright 2011 Andrés Gonzalez

%%%%%%%%%%%%%%%%%%%%

len=length(vector);

x=1:len;x=x';y=vector;

xx=1:(len-1)/(newlen-1):len;

xx=xx';

yy=interp1(x,y,xx,'linear');

newvector=yy;

end