https://in.mathworks.com/matlabcentral/answers/questionsMATLAB Answers — New Questions2021-06-16T17:57:15Ztag:in.mathworks.com,2005:Question/8580002021-06-16T17:54:43Z2021-06-16T17:54:43ZCan you help me with the while loop?I want in min years to make a final value to increase (but not exceeding 3 time the investment)
The code doesn't work
Can someone take a look?
numYears = 0;
while (FinalValue <= 3*Investment)
numYears=numYears+1;
FinalValue=Investment*power(1+Rate,numYears);
end
Tri Danghttps://in.mathworks.com/matlabcentral/profile/authors/22774898tag:in.mathworks.com,2005:Question/8579852021-06-16T17:14:24Z2021-06-16T17:54:15ZIs there a simple way to omit legend entries?
I have plotted figures where there are numerous diagonal reference lines. I only need one line to appear in the legend. However, none of the solutions I have found so far online seem to work for getting rid of the unnecessary lines. The best I can do so far (as shown in my example figure) is to remove the text "Reference line" but not the associated line. Can anyone offer advice?
I have made my legend by doing this:
refline4=plot(xref4,yref4,'Color',[0.4 0.4 0.4],'LineStyle', '-','Linewidth',0.5,'DisplayName','Reference line'); hold on
Then:
lgd=legend('Location','northwest');
When I delete
DisplayName','Reference line',
I don't get the test "Reference line" for a particular line, but I do get the line as shown in my figure. Is there a way to eliminate the lines in a way that works with the code I have? I have a lot of it and it would be very onerous to have to collect the legend labels in lists (and leave the items I don't want out of the lists) as shown in another solution I saw online. Thank you.
Srh Fwlhttps://in.mathworks.com/matlabcentral/profile/authors/18630766tag:in.mathworks.com,2005:Question/8572852021-06-16T03:03:02Z2021-06-16T17:53:41ZAdding Color Hues to Greyscale ImageHi there! I have two 500x500 greyscale images loaded in using imread() and then I fuse them using imfuse(A,B 'blend'). So the resulting image is 500x500 uint8 greyscale superimposed image.
I need to be able to add color 'hues' to the new superimposed image - such as giving it a red overlay, blue overlay etc.
Any ideas on how to do this? Thank you so much!
Matthew Peopleshttps://in.mathworks.com/matlabcentral/profile/authors/20169199tag:in.mathworks.com,2005:Question/3434712017-06-06T07:02:53Z2021-06-16T17:51:19ZHow do you pick a random number from a vector, just once?for example the vector could be v = [1 2 3] Holly Porterhttps://in.mathworks.com/matlabcentral/profile/authors/9790995tag:in.mathworks.com,2005:Question/8544802021-06-12T11:11:41Z2021-06-16T17:51:19ZApp Designer show mdl_twolink in UiAxes ComponentHi,
I am beginner in matlab and app designer, i have been playing with Peter Corke's Robotics Toolbox and i was trying to display the plot of mdl_twolink on the axes component but it keeps creating a new figure.
Is what i want possible and if it is how would i go about it?
I have read a couple of things and tried the following:
mesh(app.UIAxes,twolink.plot([Th1 Th2]))
plot(app.UIAxes, twolink.plot([Th1 Th2]))
figure(app.UIAxes);
But no successGuilherme Escarduçahttps://in.mathworks.com/matlabcentral/profile/authors/22054934tag:in.mathworks.com,2005:Question/124022011-07-26T08:58:35Z2021-06-16T17:44:54Z2D to 3D image conversionIs it possible to convert a 2D image in to 3D? Can I use VRML tool box to do this task? Is there any other techniques to perform 2D to 3D conversion in Matlab?Ganesh Radhesabhttps://in.mathworks.com/matlabcentral/profile/authors/2929616tag:in.mathworks.com,2005:Question/8579952021-06-16T17:41:47Z2021-06-16T17:41:47ZComparing 2 frames from videoI want to compare first video frames from original video and edited video, when i'm comparing r and r2 it always show error :
Error in psnr (line 3)
original_img=double(original_img);
Output argument "MSE" (and maybe others) not assigned during call to "psnr".
Error in videoStego (line 186)
[P,MSE]=psnr(r,r2);
But if i'm comparing other variables like r and b2, g and r2, etc it just run smoothly. Here is my code:
ori = VideoReader('Ori.avi');
frame = read(ori,1);
img=frame(:,:,:,1);
r=img(:,:,1);
g=img(:,:,2);
b=img(:,:,3);
edited = VideoReader('Edited.avi');
frame2 = read(v,1);
img2=frame2(:,:,:,1);
r2=img2(:,:,1);
g2=img2(:,:,2);
b2=img2(:,:,3);
[P,MSE]=psnr(r,r2);
And here is the psnr code:
function [P,MSE]=psnr(original_img,stego_img)
original_img=double(original_img);
stego_img=double(stego_img);
if (original_img==stego_img)
PSNR=100;
else
m = size(original_img,1);
n = size(stego_img,2);
d = 0 ;
for i = 1:m-1
for j = 1:n-1
d = d + (original_img(i,j) - stego_img(i,j)).^2 ;
end
end
MSE=d/(m*n);
MAX = max( abs(original_img(:)) );
PSNR= 10*log10(MAX^2/MSE);
end
P=PSNR;ArianaLaverlyhttps://in.mathworks.com/matlabcentral/profile/authors/22853260tag:in.mathworks.com,2005:Question/8570902021-06-15T18:18:01Z2021-06-16T17:57:15ZHow to print strings from a data text file that is in correlation to an indices text file?Hi everyone, I was hoping someone could help me with this tricky concept. I am trying to write a program and I don't really know how to execute it. You will see in the text files I've attached, I have one called index.txt and that has an array from 0 - 7, each index has 4 array elements (looks like this 0 1 6 2 3 1 3 2 4 0 2 1 6 4 7 ..etc). Then in the data.txt file I have another array 0 - 7 but each index includes a hexidecimal value. There are 3 categories, it should make sense when you view the text files. I'm looking for this to happen:
1.) User selects a category (Category 1, 2, and 3)
2.) User can either select index from 0-7 or an index at random.
3.) The program prints 4 strings(since the indices each contain 4 numbers) from the data.txt that is correlated to index file.
I was thinking to read line by line searching for "First Index, Second Index or Third Index to accomplish #1, and then maybe put the strings in cell arrays. This is honestly really complex for me, so any pointers on how I can get started on this would be greatly appreciated!Akana Juliethttps://in.mathworks.com/matlabcentral/profile/authors/22752688tag:in.mathworks.com,2005:Question/6163482020-10-16T17:06:55Z2021-06-16T17:35:48ZCan not install waijung blokset [SOLVED]I cannot install waijung blokset.
I have an error like;
Unable to resolve the name LibraryBrowser.StandaloneBrowser.
Error in waijung.refreshLibraryBrowser
Error in install_waijung (line 62)
waijung.refreshLibraryBrowser;
You need to use matlab with no update. just use original setup eg. 2020b, 2020a, 2018a etc. Just dont set up update after matlab installation.
What should i do?delil codeshttps://in.mathworks.com/matlabcentral/profile/authors/20002689tag:in.mathworks.com,2005:Question/3652282017-11-05T16:40:19Z2021-06-16T17:35:03ZCan a PNG image be displayed without displaying the black fill in the guide?I want to show a PNG image without a background but when I put it in the guide I fill it with the color of black
Erwin Avendañohttps://in.mathworks.com/matlabcentral/profile/authors/11402633tag:in.mathworks.com,2005:Question/8578252021-06-16T15:07:15Z2021-06-16T17:34:02ZUse Readtable() on a single-column CSV but generated multiple variable namesWhen using readtable() to read a single-column CSV file, the function reads more than one variable name.
% Read CSV data
dataset = readtable(CSVpath, "TextType","string", "ReadVariableNames", true)
vNames = dataset.Properties.VariableNames
% Expected
vNames = 1x1 cell array {'Notes'}
% Received
vNames = 1x7 cell array {'Call_1__'} {'US___'} {'Var3'} {'Var4'} {'Var5'} {'Var6'} {'Var7'}
There were 2 warnings: one telling me to use 'preserve' to preserve variable names; the other says that my variable names are too long (truncated to the max length).
Warning: Column headers from the file were modified to make them valid MATLAB identifiers before creating variable names for the table. The
original column headers are saved in the VariableDescriptions property.
Set 'VariableNamingRule' to 'preserve' to use the original column headers as table variable names.
How can I only read the one column I want?Ian Leehttps://in.mathworks.com/matlabcentral/profile/authors/22306958tag:in.mathworks.com,2005:Question/8571652021-06-15T21:26:50Z2021-06-16T17:29:04ZExtract data using ginput and fit with a formula of your choiceI am choosing two end points using ginput [x,y] = ginput(2) and then I need to separate my data set which lies between the two end points. The separated data set must be fitted into the following formula.
y(1)*exp(-(x-x(1))/T)+y(2)
y(1),x(1),y(2) are the values taken from ginput. T is a parameter that I need to determine.
How can be done?Chathuddasie Amarasinghehttps://in.mathworks.com/matlabcentral/profile/authors/19075941tag:in.mathworks.com,2005:Question/8579902021-06-16T17:29:04Z2021-06-16T17:29:04ZRequest DICOM files from a DICOM serverI'm looking for information on how to request an image from a DICOM server. This doesn't seem to be covered in the DICOM toolbox functions, and was wondering if there is a different library I should be using, From what I gather, I should be able to send a C-Get command to the server with the image series instance UID and SOP instance UID and get back a image file, similar to an FTP handshake. Has anyone experience with doing this, and if so, what libraries/functions were used?Robert Heatonhttps://in.mathworks.com/matlabcentral/profile/authors/3573772tag:in.mathworks.com,2005:Question/8579002021-06-16T15:42:29Z2021-06-16T17:27:29ZHow to change 10 cards to jack queen and kingI am making a blackjack game that involves 2 decks. I need to assign the number one cards to Ace's and the 10's to jacks, queens and kings.
my code:
%Making the deck of cards
cardValues = [1:13, 1:13, 1:13, 1:13,1:13, 1:13, 1:13, 1:13];
cardValues(cardValues>10) = 10;
if cardValues >= 10
cardValues = 10;
end
deck = [cardValues];
deck=deck(randperm(length(deck))); %this shuffles the cardsJames Keiserhttps://in.mathworks.com/matlabcentral/profile/authors/14501929tag:in.mathworks.com,2005:Question/8562252021-06-14T20:46:34Z2021-06-16T17:26:40Zplot and left axis offWhen I plot it comes with both axes in the box. How can I plot by removing right axis (or vertical line) of Box? can you please help me?
x=(1:1:10);
y= (1:2:20);
figure (1);
plot (x,y,'o-');Babu Sankhihttps://in.mathworks.com/matlabcentral/profile/authors/14694820tag:in.mathworks.com,2005:Question/8579752021-06-16T17:05:47Z2021-06-16T17:25:10ZmpLAB dsPIC "Code generation information file does not exist." [SOLVED]why am i getting this error?
Microchip Model Check before compilation
Warning: Unable to remove spaces from file path 'E:\Program Files\Microchip\xc16\v1.70'. Spaces in build-related folder paths can cause the build process to fail. For more information, see Build Process Support for Folder Names with Spaces or Special Characters. [23 similar]
### Generating code and artifacts to 'Model specific' folder structure
### Generating code into build folder: E:\calismalar\matlab_rtc_fuzzy\u1_hello_world\u1_hello_world.X
### Invoking Target Language Compiler on u1_hello_world.rtw
### Using System Target File: C:\Users\degir\AppData\Roaming\MathWorks\MATLAB Add-Ons\Toolboxes\MPLAB Device Blocks for Simulink\blocks\MCHP_dsPIC_stf.tlc
### Loading TLC function libraries
### Generating TLC interface API for custom data
.
### Initial pass through model to cache user defined code
.
### Caching model source code
### Writing main
### Writing MCHP_modelInclude.h
.
--- Single Tasking implementation ---
.
### Writing header file u1_hello_world_types.h
### Writing header file u1_hello_world.h
### Writing header file rtwtypes.h
.
### Writing source file u1_hello_world.c
### Writing header file u1_hello_world_private.h
### Writing header file rtmodel.h
### Writing source file u1_hello_world_main.c
### TLC code generation complete.
### Generating TLC interface API.
.Compile with DFP:
E:\Program Files\Microchip\MPLABX\v5.50\packs\Microchip\dsPIC33F-GP-MC_DFP\1.3.64\xc16
### MPLAB X project information extracted from buildInfo structure.
### MPLAB X project created.
.
### Processing Template Makefile: C:\Users\degir\AppData\Roaming\MathWorks\MATLAB Add-Ons\Toolboxes\MPLAB Device Blocks for Simulink\mchp\MCHP_dsPIC.tmf
COMPILATION using 9 thread.
### Created makefile E:\calismalar\matlab_rtc_fuzzy\u1_hello_world\u1_hello_world.X\u1_hello_world.mk
### Building u1_hello_world: "E:\calismalar\matlab_rtc_fuzzy\u1_hello_world\u1_hello_world.X\u1_hello_world.bat"
E:\calismalar\matlab_rtc_fuzzy\u1_hello_world\u1_hello_world.X>"E:\Program Files\Polyspace\R2021a\bin\win64\gmake" -f u1_hello_world.mk MATLAB_ROOT= ALT_MATLAB_ROOT= MATLAB_BIN= ALT_MATLAB_BIN= GENERATE_ASAP2=0 MCHP_AUTO_FLASH=0 MCHP_MULTITHREAD_COMPILATION=1 LinkWithMaster=0 OPTS="-DTID01EQ=0 -mdfp=E:\Program Files\Microchip\MPLABX\v5.50\packs\Microchip\dsPIC33F-GP-MC_DFP\1.3.64\xc16" -j 9 -l 9
Compiling: u1_hello_world_main.c
"E:/Program Files/Microchip/xc16/v1.70/bin/xc16-gcc.exe" -c -mcpu=33FJ32MC204 -omf=elf -O1 -mno-eds-warn -mconst-in-data -msmall-data -g -DTID01EQ=0 -mdfp=E:\Program Files\Microchip\MPLABX\v5.50\packs\Microchip\dsPIC33F-GP-MC_DFP\1.3.64\xc16 -I. -I".." -I"/rtw/c/ert" -I"/extern/include" -I"/simulink/include" -I"/rtw/c/src" -I"/rtw/c/src/ext_mode/common" -I"E:/calismalar/matlab_rtc_fuzzy/u1_hello_world" -I"E:/calismalar/matlab_rtc_fuzzy/u1_hello_world/u1_hello_world.X" -I"/extern/include" -I"/simulink/include" -I"/rtw/c/src" -I"/rtw/c/src/ext_mode/common" -I"/rtw/c/ert" u1_hello_world_main.c -o u1_hello_world_main.o
Compiling: u1_hello_world.c
"E:/Program Files/Microchip/xc16/v1.70/bin/xc16-gcc.exe" -c -mcpu=33FJ32MC204 -omf=elf -O1 -mno-eds-warn -mconst-in-data -msmall-data -g -DTID01EQ=0 -mdfp=E:\Program Files\Microchip\MPLABX\v5.50\packs\Microchip\dsPIC33F-GP-MC_DFP\1.3.64\xc16 -I. -I".." -I"/rtw/c/ert" -I"/extern/include" -I"/simulink/include" -I"/rtw/c/src" -I"/rtw/c/src/ext_mode/common" -I"E:/calismalar/matlab_rtc_fuzzy/u1_hello_world" -I"E:/calismalar/matlab_rtc_fuzzy/u1_hello_world/u1_hello_world.X" -I"/extern/include" -I"/simulink/include" -I"/rtw/c/src" -I"/rtw/c/src/ext_mode/common" -I"/rtw/c/ert" u1_hello_world.c -o u1_hello_world.o
elf-cc1.exe: warning: Could not open resource file: E:\Program/bin/c30_device.info
elf-cc1.exe: error: Invalid -mcpu option. CPU 33FJ32MC204 not recognized.
elf-cc1.exe: warning: Could not open resource file: E:\Program/bin/c30_device.info
elf-cc1.exe: error: Invalid -mcpu option. CPU 33FJ32MC204 not recognized.
elf-gcc.exe: Files\Microchip\MPLABX\v5.50\packs\Microchip\dsPIC33F-GP-MC_DFP\1.3.64\xc16: No such file or directory
elf-gcc.exe: Files\Microchip\MPLABX\v5.50\packs\Microchip\dsPIC33F-GP-MC_DFP\1.3.64\xc16: No such file or directory
gmake: *** [u1_hello_world_main.o] Error 255
gmake: *** Waiting for unfinished jobs....
gmake: *** [u1_hello_world.o] Error 255
### Build procedure for model: 'u1_hello_world' aborted due to an error.
Cannot propose to program chip from Matlab: Either file u1_hello_world.hex does not exist or MPLAB X API is not available on this system.
* Visit the Microchip Blockset Forum for any questions, issues, share tricks.
* Visit the Microchip Wiki for further informations and examples.
-----------------------------------------------------------------------------------------
* MPLAB X project: u1_hello_world.X then select the project folder
-----------------------------------------------------------------------------------------
***** Error detected. Links above are provided for debug purpose only (.elf file might not be current).
Build Summary 1
Elapsed: 0.11 sec
Top model targets built:
Model Action Rebuild Reason
==========================================================================
u1_hello_world Failed Code generation information file does not exist.
0 of 1 models built (0 models already up to date)
Build duration: 0h 0m 40.913s
Error(s) encountered while building "u1_hello_world"
Simulink generated c code but not .hex. delil codeshttps://in.mathworks.com/matlabcentral/profile/authors/20002689tag:in.mathworks.com,2005:Question/8546102021-06-12T15:20:19Z2021-06-16T17:24:47ZWhy can't i start the "androidFaceDetectionAndTracking"?I've started the first introductive example of the "Simulink Support Package for Android Devices" succesfully and i've also opened on Android Studio the folder ending with "ert_rtw", seeing all the java files and classes that implements this project.
But when i try to run on my Android Phone this example https://it.mathworks.com/help/supportpkg/android/ref/detect-and-track-face-on-an-android-device.html , i receive this type of error every time, and the folder "androidFaceDetectionAndTracking_ert_rtw" is always empty
Diagnostic Viewer:
Model Action Rebuild Reason =========================================================================================== androidFaceDetectionAndTracking Failed Code generation information file does not exist.
What can i do to solve the issue?
Pietro Ventrellahttps://in.mathworks.com/matlabcentral/profile/authors/14187663tag:in.mathworks.com,2005:Question/8578952021-06-16T15:42:17Z2021-06-16T17:22:06ZGetting an indexing errorI am getting this error and I don't know why.
Index in position 1 is invalid. Array indices must be positive integers or logical values.
This is the line I am getting it for:
plot(EEG.times,squeeze(EEG.data(channel_index,:,:)),'y')
I attached the data set that can be loaded to see what is going on.
I tried to attach the data file, but it is too large; even when compressed. The data file is sampleEEGdata.mat and can be found in this code downloaded from this link http://mikexcohen.com/book/AnalyzingNeuralTimeSeriesData_MatlabCode.zipRyan Griffithhttps://in.mathworks.com/matlabcentral/profile/authors/16164871tag:in.mathworks.com,2005:Question/8579152021-06-16T15:55:47Z2021-06-16T17:21:14ZCompare editfield.value to table values in app designerHello.
I wanna make an app that is comparing a value(from editfield numeric) to a table imported from excel. The table has 3 columns (z , f , d). The value has to be found in the z column. If found, the f and d colums values coresponding to z has to be displayed. Can you help me? It's my first app made in app designer.Andrei Iulianhttps://in.mathworks.com/matlabcentral/profile/authors/22852657tag:in.mathworks.com,2005:Question/8579302021-06-16T16:00:32Z2021-06-16T17:19:53ZPlot - Delete grid lines between yticksI assigned manual ticks for a plot (0.2 and 2). Is there a way to remove the gridlines in between (2) and also the small thick lines (1)? These were probably generated automatically ...
Mepehttps://in.mathworks.com/matlabcentral/profile/authors/12417523tag:in.mathworks.com,2005:Question/8579252021-06-16T16:00:25Z2021-06-16T17:19:01ZHow to read in more rows to a cell array from a text file? Hi all, I needed some help with my code. My code is meant to read in a text file (I've attached a shortened version of what the actual looks like) line by line and put only the numbers into a cell array. (I also wanted to add that I can change the String Category titles in the text document but I cannot change the content under titles.
Stored cell in MATLAB currently looks like this:
0 15 6 2 3
1 3 2 4 0
2 1 6 4 7
3 0 1 4 7
I have two major questions here:
How can I make this code produce more than just 4 rows? I either need to scan in all of the index under one cell array or create a cell array for each index category, whichever is easier. When I tried to change the 4 in the reshape line it said: "Error using reshape To RESHAPE the number of elements must not change." I got help on this and it was set as a 1x20 matrix (20 elements) and changed to a 5x4 matrix (20 elements) then transposed. I am not sure if there is a better way of doing this especially for a longer textfile.
What type of tweaks would I need to make to this same code for reading a very similar text file, except with hexadecimal values instead of decimal values? I need the hexidecimal values stored as is, not converted to anything. but the array numbers on the left. I have attached the file "data.txt" to show you what that looks like.
Here is the code so far for the index file:
fid = fopen('index.txt','r');
t = textscan(fid,'%s','delimiter','\t'); %this outputs into just one column
fclose(fid);
% converting strings to numeric types
% changing strings to empty values
t2 = t;
for n = 1:length(t2{1})
t2{1}{n} = str2num(t2{1}{n});
end
% reshapes the 1x20 row matrix into a 5x4 matrix and then transposes it
% Reshape goes down the column first
reshape(t2{1}{2},5,4)';Akana Juliethttps://in.mathworks.com/matlabcentral/profile/authors/22752688tag:in.mathworks.com,2005:Question/2735872016-03-15T11:04:02Z2021-06-16T17:18:04ZHow can I save all of the data from a simulation running in external mode to one file?Hello,
I am using a Simulink model to control a small robot. The model is compiled using the Real-Time Windows Target (ERT), and runs in external mode for 100 seconds. I have disabled the "limit data points to last" setting in the scope as well as in the configuration parameters, but the scope will only save to the workspace and display the last 10 seconds of simulation time. Additionally, the "ToFile" block is not supported by the real-time windows target. How can I save all of the data from my simulation? Is there a different block I can use?
Thank you for your help, I have spent a lot of time trying to solve this problem already.Matt Moliternohttps://in.mathworks.com/matlabcentral/profile/authors/3272516tag:in.mathworks.com,2005:Question/8576602021-06-16T11:43:58Z2021-06-16T17:16:59ZI want to generate Heatmap for irregular Time series data Dear all
I am new for matlab. I tried to plot a heat map for a dataset but it doesnt work and sample graph format is also attached for reference which i need to plot and i attached a sample data. I had tried using the below following codes. So kindly help me to resolve this issus. Thank you in advance.
x = dta(:,1);
y = dat(:,83);
z = dat(:,2:82);
tbl = table(x,y,z);
h = HeatMap(tbl,'x','y','ColorVariable','z','ColorMethod');
Error using HeatMap
Expected DATA to be one of these types:
numeric, bioma.data.DataMatrix
Instead its type was table.
Error in bioma.util.validateMatrix (line 10)
validateattributes(data, {'numeric', 'bioma.data.DataMatrix'},...
Error in HeatMap/setDisplayDataOnly (line 784)
bioma.util.validateMatrix(data, 'DATA', 'HeatMap')
Error in HeatMap/setDisplayData (line 779)
obj = setDisplayDataOnly(obj, data);
Error in HeatMap/set.Data (line 523)
setDisplayData(obj, data)
Error in HeatMap (line 366)
obj.Data = data;
vignesh mohanhttps://in.mathworks.com/matlabcentral/profile/authors/22850602tag:in.mathworks.com,2005:Question/8577652021-06-16T14:05:56Z2021-06-16T17:16:25ZFailure in initial objective function evaluation. FMINCON cannot continue.I am calculating the optimum conditions for milling process but its showing the following error on running "Failure in initial objective function evaluation. FMINCON cannot continue."Can anyone please hhelp me in solving it.I have attached the files in it too.The first file reads the data from an excel file and second file has the population balance method which has to be minimized.
The error is shown:
Output argument "y" (and maybe others) not assigned during call to "Pbmsearch".
Error in fmincon (line 567)
initVals.f = feval(funfcn{3},X,varargin{:});
Error in parameter (line 24)
[x,fval,exitflag]=fmincon(@Pbmsearch,x0,[],[],[],[],lb,ub);
Caused by:
Failure in initial objective function evaluation. FMINCON cannot continue.Aaditya Goverdhanhttps://in.mathworks.com/matlabcentral/profile/authors/19274736tag:in.mathworks.com,2005:Question/8579702021-06-16T16:54:45Z2021-06-16T17:13:44ZKindly help on "Error using horzcat Dimensions of arrays being concatenated are not consistent"Hi All,
I have an assignment to modify code given by a book. But, somehow the code contain "Error using horzcat Dimensions of arrays being concatenated are not consistent". I have tried to browse, what could be the problem, but still not get the solution. Kindly help the code below.
The error lies in X1(i,:)=[Y' dY' t];
F1=1;
F2=-1;
M1=1;
M2=1.5;
B=0.1;
K=0.2;
Coef_1=[B/M1 -B/M1 -B/M2 B/M2];
Coef_2=[K/M1 -K/M1 -K/M2 K/M2];
Y=[0.1; 0.1];
dY=[0; 0];
dt=0.1;
t=0;
tsim=200;
n=round(tsim-t)/dt;
for i=1:n
X1(i,:)=[Y' dY' t];
ddY=[F1/M1;F2/M2] - Coef_1.*dY - Coef_2.*Y;
dY=dY+dt.*ddY;
Y=Y+dt.*dY;
t=t+dt;
end
figure(1)
plot(X(:,5),X(:,1:2))
xlabel('Time (sec.)')
ylabel('Displacements')
figure(2)
plot(X(:,5),X(:,3:4))
xlabel('Time (sec.)')
ylabel('Velocities')Hafidz Akbarhttps://in.mathworks.com/matlabcentral/profile/authors/22235340tag:in.mathworks.com,2005:Question/8555952021-06-14T08:31:55Z2021-06-16T17:13:38ZHow to calculate image resolution (full-width-at-half-maximum) of a point source? Dear Matlab Expert,
I have images obtained from Monte Carlo simulations of point source. I want to calculate the images resolution at full-width-at-maximum.
The image (picture and image.mat file) and code used is given below:
V=max(max(img));
[M,N]=find(img==V);
[fwhmx, fwhmy, fwhm] =FWHM_calculation(img,N, M,pixelSize);
function [fwhm_x,fwhm_y,fwhmT]=FWHM_calculation(Image,cx,cy,pixelSize)
% this function is used to calculate the full width half maximum of image
% image: the input image, including a point source or square source in the
% center
% fwhm : the output value for fwhm
CC=ceil(cx);
CR=ceil(cy);
N=25;
Column1=CC-N:CC+N ;
Row1=CR-N:CR+N;
ROIimage=Image(Row1,Column1);
profile_x=sum(ROIimage,1);
X=1:1:2*N+1;
V=max(profile_x);
plot(X,profile_x,'r-x','LineWidth',0.7,'MarkerSize',5)
hold on
[fitresult1, gof1] =createFitSPECTfwhm2(X,profile_x,V,N);
rmse=gof1.rmse;
fwhm_x=2*sqrt(log(2))*pixelSize*fitresult1.c1
profile_y=sum(ROIimage,2);
plot(X,profile_y,'b-o','LineWidth',0.5,'MarkerSize',3)
V1=max(profile_y);
[fitresult2, gof2] =createFitSPECTfwhm2(X,profile_y,V1,N);
fwhm_y=2*sqrt(log(2))*pixelSize*fitresult2.c1
profile_yt=profile_y';
profile=(profile_x+ profile_yt)/2;
plot(X,profile,'k-*','LineWidth',0.7,'MarkerSize',5)
V=max(profile);
[fitresult2, gof2] =createFitSPECTfwhm2(X,profile,V,N);
fwhmT=2*sqrt(log(2))*pixelSize*fitresult2.c1
xlabel('Pixel Index')
ylabel('Counts')
title('Profile along Yaxis','fontSize',9)
legend('Profile along X-axis','Profile along Y-axis','Average Profile')
function [fitresult, gof] = createFitSPECTfwhm2(X, profile,maxValue,Xcenter)
%CREATEFIT(X,PROFILE_X)
% Create a fit.
%
% Data for 'untitled fit 1' fit:
% X Input : X
% Y Output: profile_x
% Output:
% fitresult : a fit object representing the fit.
% gof : structure with goodness-of fit info.
%
% See also FIT, CFIT, SFIT.
% Auto-generated by MATLAB on 26-Mar-2014 11:10:32
%% Fit: 'untitled fit 1'.
[xData, yData] = prepareCurveData( X, profile );
% Set up fittype and options.
ft = fittype( 'gauss1' );
% ft = fittype( 'gauss2' );
opts = fitoptions( ft );
opts.Display = 'Off';
% opts.Lower = [-Inf -Inf 0];
opts.Lower = [-Inf -Inf 0];
opts.StartPoint = [maxValue Xcenter 1];
opts.Upper = [Inf Inf Inf];
% opts.Upper = [Inf Inf Inf];
% Fit model to data.
[fitresult, gof] = fit( xData, yData, ft, opts );
% Plot fit with data.
figure( 'Name', 'Gaussian fit 1' );
h = plot( fitresult, xData, yData );
legend( h, 'profile_x vs. X', 'Gaussian fit 1', 'Location', 'NorthEast' );
% Label axes
xlabel( 'X' );
ylabel( 'profile_x' );
Khalid Hussainhttps://in.mathworks.com/matlabcentral/profile/authors/17352419tag:in.mathworks.com,2005:Question/8579802021-06-16T17:13:00Z2021-06-16T17:13:00ZI want to switch elements in a matrix if a condition is trueHello community,
r = 0.5;
a= 15;
b = 7.5;
p=[r + (a-2*r)*rand(n,1),r + (b-2*r)*rand(n,1)];
this is the starting position. Then I will update the position with speed v.
v = rand(n,2);
for i = 1:1000
p = p+v
After this I will check if the (spheres) are touching each other
H = pdist(p) %checks the norm of every single row with all other rows in p
if H <= 2*r
% if the norm is smaller than 2*r for example for row 2 and 5
% then the they should swap the row of the v matrix
% v(2,:) = temp_2
% v(2,:) = v (5,:)
% v(5,:) = temp_2
end
end
Is there a possibility to check this for n spheres and then swap the rows every time?
Thank you!LukasGhttps://in.mathworks.com/matlabcentral/profile/authors/17357198tag:in.mathworks.com,2005:Question/1573552014-10-04T12:27:26Z2021-06-16T17:11:58ZGrouping Figures separately into windows and tabsI have 4 plots to make, of vectors y1, y2, y3 and y4, all as a function of a vector x. I would like the first two plots to be grouped as tabs within a single Figure window, and the next two plots also grouped as tabs but in a separate window.
I tried this code:
figure
set(0,'DefaultFigureWindowStyle','docked')
plot(x,y1)
plot(x,y2)
figure
set(0,'DefaultFigureWindowStyle','normal')
plot(x,y3)
set(0,'DefaultFigureWindowStyle','docked')
plot(x,y4)
..but once tab grouping is re-enabled, plots are just added as new tabs appended to the old window rather than in a new window.
I played around with the order of the commands above but it didnt help. If anything, I only managed to get one of the plots overwritten in the same window. Please note i don't want any of the graphs to overlap, therefore "hold on" would not help.
Any suggestions? Thanks!AwedBy Matlabhttps://in.mathworks.com/matlabcentral/profile/authors/1700904tag:in.mathworks.com,2005:Question/8571752021-06-15T21:30:50Z2021-06-16T17:07:08ZReading in a text file with numbers and strings into a cell array Hi everyone, I've attached the text file here, and what I'm trying to do is read in line by line and put the strings and numbers into a cell array.
Ideally I would like to read this into a cell array that looks like this:
First Index
0 1 6 2 3
1 3 2 4 0
2 1 6 4 7
3 0 1 4 7
4 0 5 6 1
5 0 1 2 3
...etc
(I just put a bunch of spaces between the numbers but I actually need them in different cells)
(Its okay if the words/strings are all in the same cell because I'm going to try to find a way to skip that anyways)
Can anyone please assist with this? and do you think you can explain how you make it return to the next cell row after 5 columns?
When I try a code like this, I just get all the data in one cell:
t = readtable('index.txt', 'ReadVariableNames', false);
Akana Juliethttps://in.mathworks.com/matlabcentral/profile/authors/22752688tag:in.mathworks.com,2005:Question/8577002021-06-16T12:34:38Z2021-06-16T17:05:02ZConvert a Complex Number to exponential real Hi
I am looking to convert a complex number say x = 2 +j5 and I want to calculate exponential value ?
Thanks youJoggerhttps://in.mathworks.com/matlabcentral/profile/authors/7949204tag:in.mathworks.com,2005:Question/8571252021-06-15T19:17:15Z2021-06-16T17:03:17ZFast vector reshaping/permutationI'm trying to optimize a very specific vector operation, namely taking a large (2^20 x 1) vector, reshaping it, permuting the indices, and reshaping once more. To be concrete, an example:
A = rand(2^20,1); % Large vector, with one dimension a power of 2
A = A./norm(A); % Normalize just for convenience
DR = 2^6; % DR,DL,DM are powers of 2 which multiply to form the size of A
DL = 2^6;
DM = 2^8;
tic;
B = reshape(permute(reshape(A,DR,DM,DL),[2,1,3]),DM,DR*DL);
toc; % On my machine this takes ~1.2 ms
The above operation is very simple, and entirely limited in speed by the permute step - as I understand it, permutation in matlab requires the entire array to be copied, losing time for the copy to be created and the transfer to occur. I am wondering if there is any clever way to get past this requirement for this specific use-case.
I have tried putting the operation of a gpu (by calling, for instance),
A = rand(2^20,1,'gpuArray')
Which does improve the runtime by a factor of ~4 but also hurts some other areas of my application. I have not yet tried to mexify the code, but would be interested if this seems a viable way to improve as well.
Edit from the comments: Ultimately this reshaped vector/matrix "B" is then multiplied by a Matrix (DM x DM), and then permuted/reshaped back into it's original form. If there is some fast way to combine all of those operations then that would of course be even more ideal.Adam Shawhttps://in.mathworks.com/matlabcentral/profile/authors/5721030tag:in.mathworks.com,2005:Question/8578552021-06-16T15:21:23Z2021-06-16T16:59:02ZSwitch results at certain conditiong=9.81; %gravity acceleration
v=input('Enter the value of Velocity');
theta=30*pi/180;
% compute and display results
disp('time of flight(s):')
time_ground=2*v*sin(theta)/g;
disp('distance travelled(m):')
distance_traveled=v*cos(theta)*time_ground;
if distance_traveled >=10
disp('Passed')
else
disp('Failed')
end
if distance_traveled>=10;
grade=A;
switch(grade)
case distance_traveled>10
fprintf('B')
case distance_traveled>15
fprintf('A')
end
I want to make the grade change at certain condition. For example, if the distance traveled is more than 10, then the grade is B. When the distance traveled is more than 15, the grade is A. Please correct what am i doing wrong here. If possible, i dont want to get rid of the switch command. Thanks in advance.Amril Luqmanhttps://in.mathworks.com/matlabcentral/profile/authors/21868416tag:in.mathworks.com,2005:Question/4152972018-08-17T16:39:59Z2021-06-16T16:51:25ZHow to load thinkgear library and thinkgear.dll to matlab?I wanna to interface neurosky mindwave headset with matlab. I already istalled the thinkgear connecter to C drive. In C drive I could see a thinkgear.dll in "C:\Program Files (x86)\NeuroSky\ThinkGear Connector\ThinkGear Connector" address. There is no any thinkgear.dll file in "C:\Users\W.L Isuru\Documents\MATLAB". How I can load thinkgear library/thinkgear.dll/thinkgear.h file to matlab. Where it available? Is there any library called thinkgear in web to download?
Please help me..I am doing a mind controlled wheel chair..So I wanna to conncet neurosky mindwave headset to the matlab..Isuru Thiwankahttps://in.mathworks.com/matlabcentral/profile/authors/9715792tag:in.mathworks.com,2005:Question/8044312021-04-16T21:51:19Z2021-06-16T16:49:27ZHow to detect 2D objects in LiDAR data I have a Lidar scan data in which have to find the objects, the objects are more like to be in the 2- Dimensional. I am coudn't able to find the objects by using Lidar labeller and also I ahve to do it in automatically. In the LiDAR labeller, I am unable to find the objects in ROI while labelling in the app. The cubes are unable to find the exact objects, Please can anyone help me with this issue or any preforable methods for this. Ganesh Sai Doggalihttps://in.mathworks.com/matlabcentral/profile/authors/15876622tag:in.mathworks.com,2005:Question/8578702021-06-16T15:30:02Z2021-06-16T16:44:14ZCreate a matrix with elements clockwiseHello,
I would like to create a [m,n] size matrix in which the ID of the elements are created clockwise/counterclockwise.
The first element should starts in (1,1).
For example, for a matrix of size [5,8] (meaning 40 elements in total) we should have this final matrix:
This should be the result in Matlab:
Thank you in advance for your answers !Alexis Pelethttps://in.mathworks.com/matlabcentral/profile/authors/13726018tag:in.mathworks.com,2005:Question/3071672016-10-13T04:00:00Z2021-06-16T16:35:37ZHow do I reset the layout of MATLAB?How do I reset the layout of MATLAB?
MathWorks Support Teamhttps://in.mathworks.com/matlabcentral/profile/authors/4622813tag:in.mathworks.com,2005:Question/2636942016-01-13T20:06:20Z2021-06-16T16:35:32ZHow to read temperature and pressure through the bmp180?Recently I worked to read the temperature and pressure through a sensor BMP180:
First script
AC1=readRegister(bmp180, hex2dec('AA'));
AC2=readRegister(bmp180, hex2dec('AC'));
AC3=readRegister(bmp180, hex2dec('AE'));
AC4=readRegister(bmp180, hex2dec('B0'));
AC5=readRegister(bmp180, hex2dec('B2'));
AC6=readRegister(bmp180, hex2dec('B4'));
B1=readRegister(bmp180, hex2dec('B6'));
B2=readRegister(bmp180, hex2dec('B8'));
MB=readRegister(bmp180, hex2dec('BA'));
MC=readRegister(bmp180, hex2dec('BC'));
MD=readRegister(bmp180, hex2dec('BE'));
I used the variables as they appear in the sensor datasheet on page 15
Considering only the temperature:
writeRegister(bmp180, hex2dec('F4'), hex2dec('2E'))
pause(0.05)
MSBt=readRegister(bmp180, hex2dec('F6'));
LSBt=readRegister(bmp180, hex2dec('F7'));
UT=double(bitshift(int16(MSBt), 8)) + double(int16(LSBt))
X1=int16(UT)-int16(AC6)*int16(AC5)/2^15;
X2=int16(MC)*2^11/(int16(X1)+int16(MD));
B5=X1+X2;
T=(B5+8)/2^4
However this reading is not correct.
How to read correctly?
AC1 (0xAA, 0xAB) (16 bit) short ??
AC2 (0xAC, 0xAD) (16 bit) short ??
…
write 0x2E into reg 0xF4 ??
read reg 0xF6 (MSB), 0xF7 (LSB) ??
…
write 0x34 + (oss<<6) into reg 0xF4 ….. ??
Note: I am using an Arduino board Mega2560
Thank you in advance1ng3n0u5https://in.mathworks.com/matlabcentral/profile/authors/4269669tag:in.mathworks.com,2005:Question/8579602021-06-16T16:35:21Z2021-06-16T16:35:21Zplotting group size vs total member in group of particular sizeHi I fairly new to MATLAB and would like to know if there's a way to do this without involving too much looping.
so say I have a array that looks like [1 1 1 2 2 3 4 4 5 ]
I want to know the range of sizes of the groups (there's 3 ones, 2 twos, 1 three, 2 fours, 1 five) i.e I would like to have it return [1 2 3]
And I would also like to know the total number of members in each group size. In this case it would be [2 2 1] since two groups have size 1, two groups have size 2 and one gorup has size 3, etc.
Any help is appreciated!
Maggie liuhttps://in.mathworks.com/matlabcentral/profile/authors/22690855tag:in.mathworks.com,2005:Question/8568652021-06-15T13:24:58Z2021-06-16T16:30:44Zundefined function in GUIHello, can i ask why when i write code for GUI, it show
Undefined function 'multiply' for input arguments of type 'double'.?
Thank you.Lim Xiao Huihttps://in.mathworks.com/matlabcentral/profile/authors/16984066tag:in.mathworks.com,2005:Question/1083152013-12-02T18:34:55Z2021-06-16T16:30:03Zhow to split matrix by percentageI have a matrix R(u,v) and i want to split into 2 new matrices M, N.
M will be the first 10% of the rows of R and N will be the rest 90% of the rowsbabishttps://in.mathworks.com/matlabcentral/profile/authors/4695192tag:in.mathworks.com,2005:Question/8578852021-06-16T15:35:17Z2021-06-16T16:26:03ZWhy does my V returns a single scalar value?% Given
P = 3000;
E = 7e10;
h = 0.1;
b = 0.005;
t = 0.008;
w1 = 0.15;
w2 = 0.09;
L = 2;
% Input
x0=0;
dt=0.1;
x=x0:dt:L;
W=@(x) (x>=0 & x<=L/2).*w1 + (x>L/2).*w2;
w=W(x);
I=(w*h^3-(h-2*t)^3*(w-b))/12;
V=(P*x.^2).*(3*L-x)/(E*I);
Amanda Liuhttps://in.mathworks.com/matlabcentral/profile/authors/22829493tag:in.mathworks.com,2005:Question/8579552021-06-16T16:23:59Z2021-06-16T16:23:59ZHow to generate M sets of a time serie? I have to solve this exercise: Simulate data from the following model yt = α1yt−1 + α2yt−2 + εt, use α1 = 0.7 and α2 = 0.3 and for a given T generate M = 5000 sets of time series.
I can simulate data for M=1, but i don't know how to implement the simulation for M=500.
Thanks Filippo Patrignanihttps://in.mathworks.com/matlabcentral/profile/authors/18874253tag:in.mathworks.com,2005:Question/8579502021-06-16T16:18:46Z2021-06-16T16:18:46Zhow can i solve symbolic nonlinear PDE with matlabdiff(w(T__0, r), T__0, T__0) + beta__2*w(T__0, r)*diff(w(T__0, r), T__0, T__0) + diff(w(T__0, r), r, r, r, r) + 2*diff(w(T__0, r), r, r, r)/r - diff(w(T__0, r), r, r)/r^2 + diff(w(T__0, r), r)/r^3 + beta*int(diff(w(T__0, r), r)^2, r = 0 .. 1)*(diff(w(T__0, r), r, r) + diff(w(T__0, r), r)/r) = 0moslem sohrabifarhttps://in.mathworks.com/matlabcentral/profile/authors/21430326tag:in.mathworks.com,2005:Question/8579402021-06-16T16:10:03Z2021-06-16T16:16:00Zhow do I set my fully connected layer to be (3 or 2) classification output?Im working with pretrained network.
Currently, I have 3 age group (17-20, 21-40, 41-60) and another one is (female , male). My question is how to change the fully connected layer for this type of classification.
Currently I had 6 classes, 3 age group for each gender. Therefore, my classification output is 6 classes instead. Is this the correct way to classify?
Afiq Amirudinhttps://in.mathworks.com/matlabcentral/profile/authors/13601696tag:in.mathworks.com,2005:Question/8579452021-06-16T16:10:45Z2021-06-16T16:10:45ZError using coder.checkGpuInstall ( Test GPU code generation failed with the error 'emlc:compilationError' )A connection is established with Nvidia Jetson nano but, when tried to use the hardware object, we are facing with the below Error.
hwobj = jetson('hostname/ipaddress','username','password');
envCfg = coder.gpuEnvConfig('jetson');
envCfg.DeepLibTarget = 'cudnn';
envCfg.DeepCodegen = 1;
envCfg.HardwareObject = hwobj;
envCfg.Quiet = 1;
coder.checkGpuInstall(envCfg)
Cuda and cudnn not recognized:
Also installed Microsoft Visual studio, but the error is still not resolved.
How do I solve this error?
Thanks in advance!
Sainath Yarrahttps://in.mathworks.com/matlabcentral/profile/authors/22794999tag:in.mathworks.com,2005:Question/8579352021-06-16T16:09:06Z2021-06-16T16:09:06Zhello , i wants to syntax for solving following system of PDE ......thanksmukesh kumarhttps://in.mathworks.com/matlabcentral/profile/authors/19812283tag:in.mathworks.com,2005:Question/8579052021-06-16T15:52:02Z2021-06-16T16:08:26Zhow can I get y which correspond to x and then plot (x,y)??syms x y
x=[-4:1:4]
f = y^3+0.2*exp(-1*x^2)*y^2-2.2039*y^2+0.8155 == 0;jameslkhttps://in.mathworks.com/matlabcentral/profile/authors/10017153tag:in.mathworks.com,2005:Question/8522202021-06-09T18:29:33Z2021-06-16T16:05:35ZConditional Scatter plotting based on third data setThe b[e]low matrix represents 5 people (columns) over time (each row is a year). I'd like to generate some script that, returns a vector, and says something along the lines of if the entire column is 1 (male), then that person is designated as 1, if the entire column is 3 (female that has never breastfed), then that person is designated as 3, if a column is a mix of 2 (female that has breastfed at some point) and 3, then designate that person at 2.
3 1 2 1 3
3 1 2 1 3
2 1 2 1 3
2 1 2 1 3
2 1 2 1 3
2 1 2 1 3
2 1 2 1 3
2 1 3 1 3
2 1 3 1 3
2 1 3 1 3
2 1 3 1 3
2 1 3 1 3
I'd like to have a vector returned that looks like this for the above example
sex = 2 1 2 1 3
Then, I would like to use this to add (NOT DONE YET) a condition to the following plot:
figure
scatter (Resident , MC_participant_Mean) %plot of duration of residency vs mean start of exposure
xlabel('Duration of residence in community (yr)')
ylabel('Mean start of Exposure after 1970 (yr)')
title('Start of exposure vs. years in community')
So if a person has a sex status of 1 (male), then plot their {scatter (Resident , MC_participant_Mean) } data points as green; if the sex status is 2, then red; if 3, then blue....I'd like to color-code the scatter plot based on the sex status of the study participant. Is this possible??
Thank you for your time and help!!Jessica Lynne Meekshttps://in.mathworks.com/matlabcentral/profile/authors/17459556tag:in.mathworks.com,2005:Question/8577352021-06-16T13:35:03Z2021-06-16T16:00:35ZExtracting elements from one matrix and placing in anotherHello,
I have a matrix of size 97x97x117 (called yearly_array2). I'm trying to extract specific portions of the 3rd dimension (i.e. positions 7, 10, 34, 52, 79, 82, 88, 94, 100, & 115) and place those in a brand new matrix (called SLP_top_10). The expected size of the new matrix should be 1440x721x10. When I run the loop in my code, each iteration of "i" gets replaced by the next, and I'm left with the last postion (when i = 115) in the new matrix, when instead I want all 10 postions within my new matrix. What can I do, or how should I modify the following code, to retain all 10 positions of interest in my new array?
SLP_top_10 = zeros(97,97,10); %pre-allocating array of expected size
for i = [7 10 34 52 79 82 88 94 100 115] %positions of interest from yearly_array2
SLP_top_10 = yearly_array2(:,:,i);
endBrian DeCiccohttps://in.mathworks.com/matlabcentral/profile/authors/19240668tag:in.mathworks.com,2005:Question/8579202021-06-16T15:58:07Z2021-06-16T15:58:07ZHow can I find the values through the excel field that I imported to matlab?Hello all,
While I was doing my homework I have stucked at here. I have imported an excel file into matlab and the excel file consist of values such as Gender,Age,Weight,Smoking Status and Average Blood Pressure. I need to define these following two questions but I cant find out how to put it in a matlab function. Questions are,
1- What is the blood pressure of a 45-year-old, 75 kg male smoking cigarette?
2- What is the blood pressure of a 38-year-old non-smoker woman weighing 60 kg?
Any help is appreciated,Emre Eryigithttps://in.mathworks.com/matlabcentral/profile/authors/22215146