Code covered by the BSD License  

Highlights from
3D Cube Slice

from 3D Cube Slice by Oren Rosen
Enables reading 2 dim slices of 3 dim matrix stored in MAT file

flag=VarRename(filename, Target, NewName)
function flag=VarRename(filename, Target, NewName)
% VARRENAME overwrites a variable name in a Level 5 Version 6 MAT-File
% Target and NewName must be the same length
%
% Example:
% FLAG=VARRENAME('MYFILE','MICKY','MOUSE')
%
% Returns 0 if successful, -1 otherwise
%
% Author: Malcolm Lidierth 09/06
% Copyright  Kings College London 2006
% Revisions:
%
% This program is distributed without any warranty,
% without even the implied warranty of fitness for a particular purpose.

mi=StandardMiCodes();
[platform,maxsize,system_endian] = computer;

% Exit if not Windows. Comment out these lines to allow continuation on
% other platforms.
if strcmp(platform,'PCWIN')~=1
    disp(sprintf('VARRENAME: Not tested on %s platform\nExiting.\n',platform));
    return
end

% Append default .mat extension if none supplied
[pathstr, name, ext] = fileparts(filename);
if isempty(ext)
    filename=[pathstr name '.mat'];
end

flag=-1;
if nargin<3
    disp('VARRENAME: filename, targetname and newname must be specified');
    return
end

if length(Target)~=length(NewName)
    disp('VARRENAME: Old and new variable names must be the same length');
    return
end

s=where(filename,Target);
if isempty(s)
    disp(sprintf('VARRENAME: Variable %s not found',Target));
    return;
end

fh=MATOpen(filename,'r+');
    if fh<0
        return
    end
[f1, p1, fileformat]= fopen(fh);

fseek(fh,s.TagOffset+12,'bof');
NumberOfBytes=fread(fh,1,'uint32');
fseek(fh,NumberOfBytes+4,'cof');

NumberOfBytes=fread(fh,1,'uint32');
fseek(fh,NumberOfBytes,'cof');

%Name Array
N_DataType=fread(fh,1,'uint32');
if (system_endian=='L' && N_DataType>intmax('uint16')) ||...
        (system_endian=='B' && N_DataType<intmax('uint16'))
    fseek(fh,-4,'cof');
    [N_NumberOfBytes, N_DataType, values]=GetSmallDataElement(fh, fileformat);
    N_DataType=mi{N_DataType};
    N_name=char(values);
    ByteAlign(fh);
    fseek(fh,-4,'cof');
else
    N_DataType=mi{N_DataType};
    N_NumberOfBytes=fread(fh,1,'uint32');
    n=N_NumberOfBytes/sizeof(N_DataType);
    N_name=fread(fh,n,[N_DataType '=>char'])';
    fseek(fh,-n,'cof');
end

N_name=deblank(N_name);
if strcmp(N_name,Target)==1
    if strcmp(N_DataType,'int8')==1
        fwrite(fh, NewName,'int8');
        flag=0;
    end
end

fclose(fh);
end

Contact us at files@mathworks.com