Table performance / general performance / vectorizing - matlab

I implemented a 4D Interpolation in matlab, where performance is really important. The interpolation method is a nearest neighbor interpolation based on a delaunay triangulation. As I am quite new to matlab coding, I want to ask, if I should use arrays or cells instead of tables, because of their poor performance. Also the general question, if you see anything, where I can speed up my code. I already saved the mat files in v6 so this is not an option. Below the text you see the code of the main program. After that the code for the 2D interpolation.
the tables I loaded in consist of 7 coloums filled with AeroDataId, X_C coordinate, CP (pressure derivative), Mach number, lift coefficient, ReynoldsNumber and Transition. One AeroDataId belongs to in the most cases 280 x_c coordinates with the different pressure coefficients.
Filtering all the data seems to be faster than using sql queries.
clc
close
clear
%% ReynoldsNumbers and Transitions known in the database
ReynoldsNumbers=[1e6;1.5e6;2.5e6;5e6;8e6;14e6;25e6;50e6;100e6];
Transition=[0;0.1;0.2;0.3;0.4;0.5;0.6;0.7;0.8;0.9];
%% parameters
Ma=0.85;
C_l=0.345;
Tl=0.15;
Re=55e6;
AirfoilId=0;
delta=0.015;
delta_ini=0.15;
%% try to find the neighbours of the parameters, which already exist in the database
tic
Re_u=ReynoldsNumbers(ReynoldsNumbers==Re);
Tl_u=Transition(Transition==Tl);
Tl_o=[];
Re_o=[];
if isempty(Re_u)
Re_u_index=nearestpoint(Re,ReynoldsNumbers,'previous');
Re_o_index=nearestpoint(Re,ReynoldsNumbers,'next');
Re_o=ReynoldsNumbers(Re_o_index);
Re_u=ReynoldsNumbers(Re_u_index);
if Re < 1e6
Re_u=1e6;
Re_o=1.5e6;
elseif Re > 100e6
Re_u=50e6;
Re_o=100e6;
end
end
if isempty(Tl_u)
Tl_u_index=nearestpoint(Tl,Transition,'previous');
Tl_o_index=nearestpoint(Tl,Transition,'next');
Tl_u=Transition(Tl_u_index);
Tl_o=Transition(Tl_o_index);
end
toc
%% load data based on the airfoilId size of new_upper_airfoil 25000000x7 table
if AirfoilId==0
load('new_upper_airfoil_all_0');
load('new_lower_airfoil_all_0');
elseif AirfoilId==1
load('new_upper_airfoil_all_1');
load('new_lower_airfoil_all_1');
elseif AirfoilId==2
load('new_upper_airfoil_all_2');
load('new_lower_airfoil_all_2');
end
%% no need to to make all the interpolation with the whole data, only a specific delta
new_upper_airfoil=new_upper_airfoil_all(new_upper_airfoil_all.Ma < (Ma+delta_ini) & new_upper_airfoil_all.Ma > (Ma-delta_ini) & new_upper_airfoil_all.CL_res < (C_l+delta_ini) & new_upper_airfoil_all.CL_res > (C_l-delta_ini),2:7);
new_lower_airfoil=new_lower_airfoil_all(new_lower_airfoil_all.Ma < (Ma+delta_ini) & new_lower_airfoil_all.Ma > (Ma-delta_ini) & new_lower_airfoil_all.CL_res < (C_l+delta_ini) & new_lower_airfoil_all.CL_res > (C_l-delta_ini),2:7);
%% filter data for the first 2D - Interpoaltion and execute it
new_upper_airfoil1=new_upper_airfoil(new_upper_airfoil.ReynoldsNumber==Re_u & new_upper_airfoil.Transition==Tl_u,1:4);
new_lower_airfoil1=new_lower_airfoil(new_lower_airfoil.ReynoldsNumber==Re_u & new_lower_airfoil.Transition==Tl_u,1:4);
DV1=delaunay_nearest(new_upper_airfoil1, new_lower_airfoil1, Ma, C_l, delta);
DV_1=table(DV1.X_C, DV1.CP, repmat(Re_u,280,1),repmat(Tl_u,280,1),'VariableNames',{'X_C','CP','Re','Tl'});
%% secound
if ~isempty(Tl_o)
new_upper_airfoil2=new_upper_airfoil(new_upper_airfoil.ReynoldsNumber==Re_u & new_upper_airfoil.Transition==Tl_o,1:4);
new_lower_airfoil2=new_lower_airfoil(new_lower_airfoil.ReynoldsNumber==Re_u & new_lower_airfoil.Transition==Tl_o,1:4);
DV2=delaunay_nearest(new_upper_airfoil2, new_lower_airfoil2, Ma, C_l, delta);
DV_2=table(DV2.X_C, DV2.CP, repmat(Re_u,280,1), repmat(Tl_o,280,1),'VariableNames',{'X_C','CP','Re','Tl'});
else
DV_2=[];
end
%% third
if ~isempty(Re_o)
new_upper_airfoil3=new_upper_airfoil(new_upper_airfoil.ReynoldsNumber==Re_o & new_upper_airfoil.Transition==Tl_u,1:4);
new_lower_airfoil3=new_lower_airfoil(new_lower_airfoil.ReynoldsNumber==Re_o & new_lower_airfoil.Transition==Tl_u,1:4);
DV3=delaunay_nearest(new_upper_airfoil3, new_lower_airfoil3, Ma, C_l, delta);
DV_3=table(DV3.X_C, DV3.CP, repmat(Re_o,280,1),repmat(Tl_u,280,1),'VariableNames',{'X_C','CP','Re','Tl'});
else
DV_3=[];
end
%% fourth
if ~isempty(Re_o) && ~isempty(Tl_o)
new_upper_airfoil4=new_upper_airfoil(new_upper_airfoil.ReynoldsNumber==Re_o & new_upper_airfoil.Transition==Tl_o,1:4);
new_lower_airfoil4=new_lower_airfoil(new_lower_airfoil.ReynoldsNumber==Re_o & new_lower_airfoil.Transition==Tl_o,1:4);
DV4=delaunay_nearest(new_upper_airfoil4, new_lower_airfoil4, Ma, C_l, delta);
DV_4=table(DV4.X_C, DV4.CP, repmat(Re_o,280,1),repmat(Tl_o,280,1),'VariableNames',{'X_C','CP','Re','Tl'});
else
DV_4=[];
end
%% Interpolation of the 4 2D Interpolations
DV_inter=[DV_1;DV_2;DV_3;DV_4];
if size(DV_inter,1)==280
DV=DV_1(:,1:2);
% figure
% hold on
% plot(DV.X_C,-DV.CP,'bl-');
% grid on;
% xlabel('X_C');
% ylabel('Cp');
%
else
%% interpolation with inverse distance weighted interpoaltion
load('x_c0');
DV=zeros(281,2);
for x_c=1:1:280
x_c_inter=x_c0(x_c);
Find=DV_inter(DV_inter.X_C==x_c_inter,:);
cp_inter=IDW(Find.Re, Find.Tl,Find.CP,Re,Tl,-2,'ng',2);
DV(x_c,:)=[x_c_inter,cp_inter];
end
DV(281,:)=DV(1,:);
figure
hold on
plot(DV(:,1),-DV(:,2),'r-');
grid on;
xlabel('X_C');
ylabel('Cp');
end
function DV = delaunay_nearest(new_upper_airfoil,new_lower_airfoil,Ma,C_l,delta)
Error=true;
load('x_c0');
while(Error)
%% build table for the pressure distribution
DV=array2table(zeros(280,2),'VariableNames',{'X_C','CP'});
%% another smaller delta for the interpolation (if too small the exception will be catched and the interpolation is restarted with a higher delta
new_upper_airfoil_loop=new_upper_airfoil(new_upper_airfoil.Ma < (Ma+delta) & new_upper_airfoil.Ma > (Ma-delta) & new_upper_airfoil.CL_res < (C_l+delta) & new_upper_airfoil.CL_res > (C_l-delta),:);
new_lower_airfoil_loop=new_lower_airfoil(new_lower_airfoil.Ma < (Ma+delta) & new_lower_airfoil.Ma > (Ma-delta) & new_lower_airfoil.CL_res < (C_l+delta) & new_lower_airfoil.CL_res > (C_l-delta),:);
%% try to build the delaunay triangulation
try
DT=delaunayTriangulation(new_upper_airfoil_loop.Ma,new_upper_airfoil_loop.CL_res);
% figure
% hold on;
% triplot(DT);
% plot(Ma,C_l,'ro');
%% find nearest neighbor
pointindex=dsearchn(DT.Points,[Ma,C_l]);
point=DT.Points(pointindex,:);
Error=0;
catch
delta=delta+0.005;
disp('Die Deltas wurden um 0.005 erhöht, da der Bereich der Daten zu klein war.');
continue;
end
%% search for the nearest neighbor
new_upper_airfoil_loop=new_upper_airfoil_loop(new_upper_airfoil_loop.Ma==point(1,1) & new_upper_airfoil_loop.CL_res==point(1,2),1:2);
new_lower_airfoil_loop=new_lower_airfoil_loop(new_lower_airfoil_loop.Ma==point(1,1) & new_lower_airfoil_loop.CL_res==point(1,2),1:2);
%% 2D Interpolation for all 280 points of the airfoil with the same x/c coordinates
for x_c=1:1:280
x_c_inter=x_c0(x_c);
%% upper_airfoil
if x_c < 146
FIND=new_upper_airfoil_loop(abs(new_upper_airfoil_loop.X_C-x_c_inter)<0.0005,:);
if(isempty(FIND))
leftNeighborIndex=nearestpoint(x_c_inter,new_upper_airfoil_loop.X_C,'previous');
if isnan(leftNeighborIndex)
leftNeighborIndex=1;
end
rightNeighborIndex=leftNeighborIndex+1;
if rightNeighborIndex > height(new_upper_airfoil_loop)
rightNeighborIndex=leftNeighborIndex-1;
end
average=interp1([new_upper_airfoil_loop.X_C(leftNeighborIndex,:),new_upper_airfoil_loop.X_C(rightNeighborIndex,:)], [new_upper_airfoil_loop.CP(leftNeighborIndex,:),new_upper_airfoil_loop.CP(rightNeighborIndex,:)], x_c_inter, 'linear','extrap');
FIND.X_C(1,:)=x_c_inter;
FIND.CP(1,:)=average;
DV(x_c,:)=FIND;
else
FIND.X_C(1,1)=x_c_inter;
DV(x_c,:)=FIND(1,:);
end
end
%% lower airfoil
if x_c > 145
FIND=new_lower_airfoil_loop(abs(new_lower_airfoil_loop.X_C-x_c_inter)<0.00008,:);
if(isempty(FIND))
leftNeighborIndex=nearestpoint(x_c_inter,new_lower_airfoil_loop.X_C,'previous');
if isnan(leftNeighborIndex)
leftNeighborIndex=height(new_lower_airfoil_loop);
end
rightNeighborIndex=leftNeighborIndex-1;
average=interp1([new_lower_airfoil_loop.X_C(leftNeighborIndex,:),new_lower_airfoil_loop.X_C(rightNeighborIndex,:)], [new_lower_airfoil_loop.CP(leftNeighborIndex,:),new_lower_airfoil_loop.CP(rightNeighborIndex,:)], x_c_inter, 'linear','extrap');
FIND.X_C(1,:)=x_c_inter;
FIND.CP(1,:)=average;
DV(x_c,:)=FIND;
else
FIND.X_C(1,1)=x_c_inter;
DV(x_c,:)=FIND(1,:);
end
end
end
end
end

Related

How to do an animate plot in MATLAB from a sequence of matrices

I have code that uses Wolff's Algorithm to simulate the XY Model in MATLAB and I want to implement a pcolor/color map to demonstrate each spin according to their angles across the system. But I want it to be live and changing as the angles change.
Any idea how to do this?
This is an example of how I want it to look https://i.stack.imgur.com/aSp7s.png
If you save each snapshot of the lattice in a cell array A{t}, you can use the following function to view and save it as a video (if fileName is not empty, the function saves an mp4 video).
Another option is to adapt the function view_lattice to run your simulation (which, honestly, I wouldn't recommend, for performance issues). I will mark where you should edit for doing a "live" simulation
This is at least MATLAB R2019b (although it may be compatible with earlier versions, but no guarantee).
File view_lattice.m
function view_lattice(A,fileName)
% for a 'live' simulation, you will have to remove A from the input
% parameters and add the ones you need for the XY Wolff algorithm,
% which will be used to calculate each configuration A in the time loop below
% you will also need to remove the assert statements for 'live' simulation
%
% otherwise, you save snapshots from your simulation
% and use this function as is
%
% A -> A{k}[m,n] snapshot k containing the angles of spins in lattice site at row m and col n
% fileName -> if contains string, then records a video with the snapshots and name it with this string
assert(iscell(A) && all(cellfun(#(a)isnumeric(a) && ismatrix(a),A)),'A must be cell of numeric matrices');
assert(ischar(fileName),'fileName must be either an empty char or contain a file name');
recordVideo = ~isempty(fileName);
if recordVideo
vw = setup_video(fileName);
else
vw = [];
end
% setting some default axis properties to speed-up plotting
set(0,'DefaultAxesPlotBoxAspectRatio',[1 1 1],'DefaultAxesDataAspectRatioMode','manual','DefaultAxesDataAspectRatio',[1,1,1],'DefaultAxesNextPlot','replace');
fh = figure;
ax=axes;
for t = 1:numel(A) % for 'live' simulation, this loop should be the time loop
% here you calculate the new configuration A
% and call the function below with A instead of A{t}
vw = record_frame(vw,fh,ax,A{t},t,recordVideo);
end
% any video to close?
if recordVideo
vw.close();
end
end
function vw = record_frame(vw,fh,ax,A,t,recordVideo)
imagesc(ax,A);
title(ax,sprintf('snapshot %g',t)); % if you want, y
axis(ax,'square');
daspect(ax,[1,1,1]);
pause(0.01);
if recordVideo
vframe = getframe(fh);
vw.writeVideo(vframe);
end
end
function vw = setup_video(fileName)
vid_id = num2str(rand,'%.16g');
vid_id = vid_id(3:6);
vid_id = [fileName,'_',vid_id];
% Initialize video
vw = VideoWriter([vid_id,'.mp4'], 'MPEG-4'); %open video file
vw.Quality = 100;
vw.FrameRate = 16;
vw.open();
end
Test script: test.m
clearvars
close all
A = cell(1,30);
for t = 1:numel(A)
% creating a sequence of random snapshots only for illustration
A{t} = rand(20,20);
end
% viewing the animation and saving it as a video with name test
view_lattice(A,'test');
Output

How to plot Phasor in MATLAB

I have been working on Data Compression through SDT algorithm. I have been given a task to compress the data having 20001 points and I successfully compressed it into 944 points. Now I want to plot phasors in MATLAB. How to do it?
I used plot3 command but unfortunately could not get the desired result.
My code:
clear
clc
load('s.mat');
[N,~]=size(a(:,1));
b=[]
s=1; %storage point
a(s,6)=a(1,2); %vs, store the first phasor
a(s,5)=a(1,1); %ts
a(s,7)=a(1,3); %alphas
for n=3:1:N
p=n-1;
vp=a(p,2);
tp=a(p,1);
alphap=a(p,3);
vn=a(n,2);
tn=a(n,1);
alphan=a(n,3);
vs=a(s,6); %vs
ts=a(s,5);%ts
alphas=a(s,7);%alphas
for i=s+1:n-1 %Condtion for Vi and Current Points
ti=a(i,1);
alphai=a(i,3);
vi=a(i,2)*(cos(alphai)+1i*sin(alphai));%Phasors (Vi)
vcomp=((vn-vs)/(tn-ts))*(ti-ts)+vs;
alphacomp=((alphan-alphas)/(tn-ts))*(ti-ts)+alphas;
vcpx=vcomp*(cos(alphacomp)+1i*sin(alphacomp));%Phasors (Vcomp)
%Etve condition to convert ploar into rectangular components
e_TVE=norm((vcpx-vi),2)/norm(vi,2);%etve condition
a(i,4)=e_TVE;
if e_TVE<=0.001
continue;
else
s=p;
a(s,6)=vp; %vs
a(s,5)=tp;%ts
a(s,7)=alphap;%alps
% a(s,8)=a(p,6)*(cos(a(p,7))+1i*sin(a(p,7))); %Phasors of Storage point
break;
end
end
end
a(n,6)=vn; %vs,reserve the last data
a(n,5)=tn;%ts
a(n,7)=alphan;%alps
x=1;
for y=1:1:20001
if a(y,5)>0 || a(y,6)>0 || a(y,6)>0
b(x,1)=a(y,5);
b(x,2)=a(y,6);
b(x,3)=a(y,7);
x=x+1;
end
end
Figure 1 is the original (Uncompressed data):
Figure 2 is the compressed data result:
Figure 3 is the desired result:

Passing parameters to a Matlab function

I have a very simple question, but I didn't figure out how to solve this.I have the function definition below:
function model = oasis(data, class_labels, parms)
% model = oasis(data, class_labels, parms)
%
% Code version 1.3 May 2011 Fixed random seed setting
% Code version 1.2 May 2011 added call to oasis_m.m
% Code version 1.1 May 2011 handle gaps in class_labels
%
% Input:
% -- data - Nxd sparse matrix (each instance being a ROW)
% -- class_labels - label of each data point (Nx1 integer vector)
% -- parms (do sym, do_psd, aggress etc.)
%
% Output:
% -- model.W - dxd matrix
% -- model.loss_steps - a binary vector: was there an update at
% each iterations
% -- modeo.parms, the actual parameters used in the run (inc. defaults)
%
% Parameters:
% -- aggress: The cutoff point on the size of the correction
% (default 0.1)
% -- rseed: The random seed for data point selection
% (default 1)
% -- do_sym: Whether to symmetrize the matrix every k steps
% (default 0)
% -- do_psd: Whether to PSD the matrix every k steps, including
% symmetrizing them (defalut 0)
% -- do_save: Whether to save the intermediate matrices. Note that
% saving is before symmetrizing and/or PSD in case they exist
% (default 0)
% -- save_path: In case do_save==1 a filename is needed, the
% format is save_path/part_k.mat
% -- num_steps - Number of total steps the algorithm will
% run (default 1M steps)
% -- save_every: Number of steps between each save point
% (default num_steps/10)
% -- sym_every: An integer multiple of "save_every",
% indicates the frequency of symmetrizing in case do_sym=1. The
% end step will also be symmetrized. (default 1)
% -- psd_every: An integer multiple of "save_every",
% indicates the frequency of projecting on PSD cone in case
% do_psd=1. The end step will also be PSD. (default 1)
% -- use_matlab: Use oasis_m.m instead of oasis_c.c
% This is provided in the case of compilation problems.
%
I want to use this function, but I don't figure how to set the parameters, or use the default values. What is the variable parms in this case, it is an object that keep all the other variables? Can I make something python like syntax where we put the name of the parameter plus value? For example:
model = oasis(data_example, labels_example, agress = 0.2)
Additionally, If I have understood correctly, I get two Objects in the Output, which is model and modeo, so I need to make this call to receive all contents this function returns?
[model,modeo] = oasis(data_example, labels_example, ?(parms)?)
From your function definition it seems like params is simply a placeholder for the parameters. Typically the parameters themselves are passed as pairs of inputs in the form:
model = oasis(data, class_labels, 'do_sym',do_symValue, 'do_psd', do_psdValue,...)
where do_symValue and do_psdValue are the values you want to pass as the respective parameters.
As for the functions return value, it returns a single struct with members W, loss_steps, and parms. I believe that what you thought as a second output (modelo) is simply a typo in the text - at least based on the function's definition.
From the documentation above, I don't know which one is the right, but there are two common ways for optional parameters in matlab.
parameter value pairs:
model = oasis(data, class_labels, 'do_sym',1,'do_psd',0)
structs:
params.do_sym=1
params.do_psd=0
model = oasis(data, class_labels, params)
Probably one of these two possibilities is right.

Hill climbing in 7D space

I have below function in 7D space (means x=(x1,x2,x3,x4,x5,x6,x7)) and I want find the minimum point of this function with hill climbing in matlab.
I found this link useful but I don't know how can I implement my function in Matlab.
Update:
I implement below code but I don't really know if it is correct.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Create a grid of states %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clear all ,close all;
n=7;
range=[-32.768:0.1:32.768];
x=[0,0,0,0,0,1,1];
F=-20*exp(-0.2*sqrt(1/n*sum(x.^2)))-exp(1/n*sum(cos(2*pi*x)))+20 +exp(1);
F1=zeros(7,2);
best = -100000000; % Best value found so far.
for (j=1:20)
% Pick a starting location at random, and try and find the maximum state by hill climbing.
% Repeat this a (to be precise, repeat it until j = 20).
s=floor(100*rand(7,1)) ;
% Generate successors, and compute the one with the maximum value.
% Only consider states to the N, S, E, W, and NoMove.
for (i=1:100)
% Find successors
S0=s;
F0=-20*exp(-0.2*sqrt(1/n*sum(S0.^2)))-exp(1/n*sum(cos(2*pi*S0)))+20 +exp(1);
for tt=1:7
arr=[0;0;0;0;0;0;0];
arr(tt)=1;
S1=s+arr;
F1(tt,1)=-20*exp(-0.2*sqrt(1/n*sum(S1.^2)))-exp(1/n*sum(cos(2*pi*S1)))+20 +exp(1);
arr(tt)=-1;
S1=s+arr;
F1(tt,2)=-20*exp(-0.2*sqrt(1/n*sum(S1.^2)))-exp(1/n*sum(cos(2*pi*S1)))+20 +exp(1);
end
[v,vi] = max([F1(:,1)',F1(:,1)',F0]);
arr=[0;0;0;0;0;0;0];
index=mod(vi,7);
if(index==0)
index=7;
end
if(vi<=7 && vi ~= 15)
arr(index)=1;
s=s+arr;
elseif(vi>7 && vi ~= 15)
arr(index)=-1;
s=s+arr;
else
s=s ; %% for better understanding
end
end
end
I implement it here. I hope be useful for another reader that have problem.
clear all ,close all;
clc;
n=7;
range=[-32.768:0.1:32.768];
%x=[0,0,0,0,0,1,1];
%F=-20*exp(-0.2*sqrt(1/n*sum(x.^2)))-exp(1/n*sum(cos(2*pi*x)))+20 +exp(1);
F1=zeros(7,2);
for (j=1:20)
s=floor(rand(7,1)*64-32) ;
i=0;
convergence=0;
while(convergence~=1 && i <10000)
% Find successors
S0=s;
F0=-20*exp(-0.2*sqrt(1/n*sum(S0.^2)))-exp(1/n*sum(cos(2*pi*S0)))+20 +exp(1);
%step=rand();
step=0.005; % this is step of climbing
for tt=1:7
arr=[0;0;0;0;0;0;0];
arr(tt)=step;
S1=s+arr;
F1(tt,1)=-20*exp(-0.2*sqrt(1/n*sum(S1.^2)))-exp(1/n*sum(cos(2*pi*S1)))+20 +exp(1);
arr(tt)=-step;
S1=s+arr;
F1(tt,2)=-20*exp(-0.2*sqrt(1/n*sum(S1.^2)))-exp(1/n*sum(cos(2*pi*S1)))+20 +exp(1);
end
[v,vi] = max([F1(:,1)',F1(:,1)',F0]);
arr=[0;0;0;0;0;0;0];
index=mod(vi,7);
if(index==0)
index=7;
end
if(vi<=7 && vi ~= 15)
arr(index)=step;
s=s+arr;
elseif(vi>7 && vi ~= 15)
arr(index)=-step;
s=s+arr;
else
convergence=1; %this means no neighbor has better value than current a
%maybe this point be local optimom
end
i=i+1;
end
disp('*****************************');
disp(sprintf('Step of convergence %i:',i));
disp('coordination of optimum point :');
disp(s');
disp('*****************************');
end

matlab - is there a function which echo text of file ?

Since it is not possible to have a script and a function definition in the same file , I thought to echo the function which I want to attach in the script such that I get a script with function code and then some usage with this function .
For example -
func1.m
function [result] = func1(x)
result=sqrt(x) ;
end
script1.m
echo(func1.m) ;
display(func1(9))
Desire output for script1.m
function [result] = func1(x)
result=sqrt(x) ;
end
display(func1(9))
3
Have you any idea for that ?
Since a convoluted solution was already proposed, why not stating the obvious?
Matlab has a built-in command that does exactly what you want. It is called type:
>> type('mean')
will give you this:
function y = mean(x,dim)
%MEAN Average or mean value.
% For vectors, MEAN(X) is the mean value of the elements in X. For
% matrices, MEAN(X) is a row vector containing the mean value of
% each column. For N-D arrays, MEAN(X) is the mean value of the
% elements along the first non-singleton dimension of X.
%
% MEAN(X,DIM) takes the mean along the dimension DIM of X.
%
% Example: If X = [0 1 2
% 3 4 5]
%
% then mean(X,1) is [1.5 2.5 3.5] and mean(X,2) is [1
% 4]
%
% Class support for input X:
% float: double, single
%
% See also MEDIAN, STD, MIN, MAX, VAR, COV, MODE.
% Copyright 1984-2005 The MathWorks, Inc.
% $Revision: 5.17.4.3 $ $Date: 2005/05/31 16:30:46 $
if nargin==1,
% Determine which dimension SUM will use
dim = min(find(size(x)~=1));
if isempty(dim), dim = 1; end
y = sum(x)/size(x,dim);
else
y = sum(x,dim)/size(x,dim);
end
You could use this:
function echo(mfile)
filename=which(mfile);
if isempty(filename)
fprintf('Invalid input - check you are inputting a string.');
return;
end
fid=fopen(filename,'r');
if (fid<0)
fprintf('Couldn''t open file.');
end
file=fread(fid,Inf);
fclose(fid);
fprintf('%s',file);
end
This will open a file, read it, and print it. Note that you need to provide the input as a string, i.e. with single quotes around it, and need to have '.m' at the end:
echo('fread.m')
Not
echo(fread.m) % This won't work
echo('fread') % This won't work
Just for completeness, there's also dbtype which prepends line numbers.